module UsersHelper
# Returns the Gravatar (http://gravatar.com/) for the given user.
def gravatar_for(user, options = { size: 10 })
gravatar_id = Digest::MD5::hexdigest(user.email.downcase)
size = options[:size]
gravatar_url = "http://gravatar.com/avatar/#{gravatar_id}.png?s=#{size}"
image_tag(gravatar_url, alt: user.name, class: "gravatar")
end
end
I have used this code and assumed it would vary the size of the gravatar, however it seems to have no affect on it? Am I missing something? I have also tried to change the value in the view to:
<%= gravatar_for #user, size: 10 %>
<%= #user.name %>
To see if this changes anything, to no avail.
assuming your helper module is as below
module UsersHelper
# Returns the Gravatar (http://gravatar.com/) for the given user.
def gravatar_for(user, options = { size: 50 })
gravatar_id = Digest::MD5::hexdigest(user.email.downcase)
size = options[:size]
gravatar_url = "https://secure.gravatar.com/avatar/#{gravatar_id}?s=#{size}"
image_tag(gravatar_url, alt: user.name, class: "gravatar")
end
end
then pass in your size in the view
<%= gravatar_for #user, :size => 30 %>
Related
I'm new to Rails and i've been trying out Active Job and Action Cable and also Presenter and I've searched all over the place but not being able to figure it out.
so my question is that is there any way to use presenter in a partial and render it outside a controller(in ActiveJob for example)?
below is what i am wanting to achieve:
I have a message system(more like an email), with conversations controller and messages controller. What I want to achieve is when somebody starts a new conversation, if the receiver is on the conversation index page, the new conversation automatically appends to their index view.(like in emails) by using ActionCable
So, my conversation.rb
class Conversation < ApplicationRecord
has_many :messages, dependent: :destroy
after_create_commit { ConversationBroadcastJob.perform_later(self) }
conversation_broadcast_job.rb
class ConversationBroadcastJob < ApplicationJob
queue_as :default
def perform(conversation)
ActionCable.server.broadcast "conversations:#{conversation.receiver_id}",
{convo: render_conversation(conversation)}
end
private
def render_conversation(conversation)
ConversationsController.render(partial: 'conversations/conversation',
locals: {conversation: conversation, var: 'not'})
end
end
and my _conversation.html.erb, I used a Presenter by following this episode of RailCast
<% present conversation do |conversation_presenter| %>
<div class="conversation <%=conversation_presenter.css(var)%>"
id="conversation_<%= conversation.id %>"
data-sender-id='<%= conversation_presenter.sender_id%>'>
<%=conversation_presenter.avatar%>
<div class="conversation-counterpart-name conversation-info truncate">
<%=conversation_presenter.name(var) %>
</div>
<div class='conversation-subject conversation-info truncate'>
<%=link_to conversation_messages_path(conversation),
class:'link-gray truncate' do |n|%>
<%=conversation_presenter.subject %>
<div class='last-message truncate'>
<%=conversation_presenter.last_message%>
</div>
<% end %>
</div>
<div class="conversation-date conversation-info">
<%=conversation_presenter.last_date%>
</div>
</div>
<% end %>
The present method is defined in ApplicationHelper
def present(object, klass = nil)
klass ||= "#{object.class}Presenter".constantize
presenter = klass.new(object, self)
yield presenter if block_given?
presenter
end
conversation_presenter.rb
class ConversationPresenter < BasePresenter
presents :conversation
delegate :subject, to: :conversation
def name(var)
if conversation.sender_id == var.id
conversation.receiver.name
else
conversation.sender.name
end
end
def last_date
if conversation.last_msg.nil?
conversation.render_date
else
conversation.last_msg.render_date
end
end
def last_message
conversation.last_msg.content unless conversation.last_msg.nil?
end
def avatar
h.image_tag('avatar.svg', size: 30, class:'conversation- counterpart-avatar')
end
def css(var)
"unread" unless
conversation.read || (!conversation.last_msg.nil? && conversation.last_msg.wrote_by(var))
end
def sender_id
if conversation.last_msg.nil?
conversation.sender_id
else
conversation.last_msg.author_id
end
end
end
The problem starts from here, the partial won't get rendered in the ActiveJob, because of the conversation presenter I assume.
So my question is that is there anyway to use presenter with rendering outside a controller?
Please let me know if you need any information about other part of my codes
Thanks!
I used the following code enough to run it from ActiveJob:
ApplicationController.new.render_to_string(
:template => 'users/index',
:layout => 'my_layout',
:locals => { :#users => #users }
)
Extracted from https://makandracards.com/makandra/17751-render-a-view-from-a-model-in-rails
try use
ConversationsController.render -> ApplicationController.renderer.render
this is helping me once.
def render_conversation(conversation)
renderer=ApplicationController.renderer.new
renderer.render(partial: 'conversations/conversation',
locals: {conversation: conversation, var: 'not'})
end
Below works in Rails 5:
ApplicationController.render(
:template => 'users/index',
:layout => 'my_layout',
:assigns => { users: #users }
)
Example: this can be in jobs folder or any other place u wish.
i used in jobs (jobs/invoice_job.rb)
invoice_obj = Invoice.first
# Process the pdf_attachement in any way you want
pdf_attachement = WickedPdf.new.pdf_from_string(
ApplicationController.render(template: 'invoices/invoice_pdf.html.erb', layout: 'layouts/pdf.html.haml', assigns: { invoice: invoice })
)
use it in a view like below: (views/invoices/invoice_pdf.html.erb)
<%
#invoice = assigns[:invoice]
%>
<%= render 'invoices/invoice_pdf_template' %> <!-- generate your pdf html -->
pdf layout: (layouts/pdf.html.haml)
!!!
%html
%head
%title RailsWickedPdf
= wicked_pdf_stylesheet_link_tag "application", :media => "all"
= wicked_pdf_stylesheet_link_tag "https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css", media: "all"
= wicked_pdf_javascript_include_tag "application"
= csrf_meta_tags
%body
= yield
Refer here for more infomation.
#social_list
= form_tag notes_path, class: 'form clearfix', id: 'add_post_form',multipart: true, remote: true
.control-group
= text_area_tag "comment[text]", '', :placeholder => 'Post to the community', :cols => nil, :rows => nil, :class => 'mention expand-without-submit'
= file_field_tag "picture", id:'image_upload', accept: 'image/png,image/gif,image/jpeg'
= submit_tag "Post your message", class: 'btn btn-success btn-mini'
= form_tag images_path
= submit_tag 'asad'
= render "dashboards/activity_stream_filter"
I want to add second form but it is giving me this error.
syntax error, unexpected keyword_ensure, expecting $end
I guess some scoping issue is messed up or is the possible to have multiples form in single page ?
The form_tag method takes a block for the form contents. In your first form you have’t provided a block at all since nothing is indented below it. In the second case there is content indented below, but you haven’t included the do. This second case is causing the syntax error.
What I think you want is
#social_list
- # note 'do' added to this line:
= form_tag notes_path, class: 'form clearfix', id: 'add_post_form',multipart: true, remote: true do
- # this section indented:
.control-group
= text_area_tag "comment[text]", '', :placeholder => 'Post to the community', :cols => nil, :rows => nil, :class => 'mention expand-without-submit'
= file_field_tag "picture", id:'image_upload', accept: 'image/png,image/gif,image/jpeg'
= submit_tag "Post your message", class: 'btn btn-success btn-mini'
- # 'do'added to next line
= form_tag images_path do
= submit_tag 'asad'
= render "dashboards/activity_stream_filter"
I added the simple_captcha gem and I'm receiving an error in the server when I load up the form that it's located on. I'm not sure how to go about fixing this. Judging my the research I've done on google it appears to be an ImageMagick issue but I'm not entirely sure.
SimpleCaptcha::SimpleCaptchaData Load (0.2ms) SELECT "simple_captcha_data".* FROM "simple_captcha_data" WHERE "simple_captcha_data"."key" = '406a6bd66e520eef7f24a13c2cc8c5b23d3749e8' LIMIT 1
CACHE (0.0ms) SELECT "simple_captcha_data".* FROM "simple_captcha_data" WHERE "simple_captcha_data"."key" = '406a6bd66e520eef7f24a13c2cc8c5b23d3749e8' LIMIT 1
StandardError (Error while running convert: convert: unable to read font `/usr/local/share/ghostscript/fonts/n019003l.pfb' # error/annotate.c/RenderFreetype/1125.
convert: Postscript delegate failed `/var/tmp/magick-4563zAoZ5QYyFe6C': No such file or directory # error/ps.c/ReadPSImage/833.
convert: no images defined `/var/folders/6b/tq59gs0d1f7bp_zg41cf6fqm0000gn/T/simple_captcha20130626-4555-1yk8sq1.jpg' # error/convert.c/ConvertImageCommand/3078.
):
simple_capthca.rb
SimpleCaptcha.setup do |sc|
# default: 100x28
sc.image_size = '120x40'
# default: 5
sc.length = 6
# default: simply_blue
# possible values:
# 'embosed_silver',
# 'simply_red',
# 'simply_green',
# 'simply_blue',
# 'distorted_black',
# 'all_black',
# 'charcoal_grey',
# 'almost_invisible'
# 'random'
sc.image_style = 'simply_green'
# default: low
# possible values: 'low', 'medium', 'high', 'random'
sc.distortion = 'medium'
sc.image_magick_path = '/usr/local/bin/' # you can check this from console by running: which convert'
end
reservations_controller.rb
def create
#restaurant = Restaurant.find(params[:restaurant_id])
#reservation = #restaurant.reservations.build(date: DateTime.new(params[:date]["date(1i)"].to_i, params[:date]["date(2i)"].to_i, params[:date]["date(3i)"].to_i), time: (params[:time][:hour]).to_i)
if #reservation.valid_with_captcha?
#reservation.save
#restaurant.owner.send_reservation_notification(#reservation)
redirect_to restaurant_path(Restaurant.find(params[:restaurant_id]))
else
flash[:error] = "Captcha incorrect. You enterd the wrong digits."
redirect_to :back
end
end
new.html.erb
<h1>Reserve your table.</h1>
<br/>
<div class="reservation-form">
<%= form_for([#restaurant, #reservation]) do |f| %>
<%= date_select :date, "date" %><br/>
<%= select_hour Time.now, :ampm => true, :prefix => :time %><br/><br/>
<%= f.simple_captcha :label => "Prove that you're not a robot." %><br/>
<%= f.submit "Make reservation", class: "btn btn-primary" %>
<% end %>
</div>
Reservation.rb
class Reservation < ActiveRecord::Base
attr_accessible :restaurant_id, :date, :time
belongs_to :restaurant
apply_simple_captcha
end
Probably, you need to install ghostscript after you have imagemagic installed.
I am using slim templates for my rails application. But something strang is happening. In my application template I have a form like so:
= form_tag search_path, class:'navbar-search pull-left', remote: true
= text_field_tag :term, nil, class: 'search-query span2', placeholder: 'Search'
That renders well on my page and the search form is working fine. However in my sign up partial I have:
= form_tag '/auth/identity/callback'
- if #identity && #identity.errors.any?
div.error
h2 =pluralize(#identity.errors.count, 'error')
|prohibited this account from being saved:
ul
- #identity.errors.full_messages.each do |msg|
li =msg
h1
i.iconbig-lock
| Sign In
div.login-fields
p Sign In using your email:
div.field
= label_tag :auth_key, 'Email'
= text_field_tag :auth_key, nil, class: 'input login username-field', placeholder: 'Email'
div.field
= label_tag :password, 'Password'
= password_field_tag :password, nil, class:'login password-field', placeholder: 'password'
div.login-actions
= submit_tag 'Login', class: 'btn-signin btn btn-primary'
div.login-social.marg10-btm
p Sign in using social network:
a.btn
= image_tag 'twitter-18.png'
| Signin with twitter
a.btn href="/auth/facebook"
= image_tag 'facebook-18.png'
| Signin with Facebook
the form tag doesn't render, but all sub elements text fields (including the 'authenticity_token') renders fine.
I play around abit and notice that the page only allow 1 form_tag. Ones created after the first never renders. I been looking on google for a while and could not figure why. Any ideas?
from leogalmeida # github
Try adding 'do' in the end of both form tags:
= form_tag search_path, class:'navbar-search pull-left', remote: true do
= form_tag '/auth/identity/callback' do
I'm having trouble getting my view to render. I think I know why I'm getting the error:
undefined method `name' for nil:NilClass
Extracted source (around line #21): (showing 18-24)
<ul>
<%= form_tag(default_hero_user_path, :method=>'post') do %>
<%= label_tag "Name" %>
<%= text_field_tag "name", #user.default_hero.name %> #line 21
<%= submit_tag 'Set hero', class: "btn btn-large btn-primary" %>
<% end %>
</ul>
I know you can't call .name on a nil object but I don't understand why #user.default_hero is nil. I want the user to be able to set their 'hero' but having trouble setting the default obviously.
Here is the users controller:
# creates or updates the default hero
def default_hero
#user = User.find(params[:id])
hero = #user.default_hero
if hero.nil?
# we don't have a default hero so we need to add one'
hero = Hero.new
#user.heros << hero
end
hero.default = true
hero.name = params[:name]
hero.save
redirect_to #user # shows the user again to see any updates
end
And here is where I believe I am having the problem in setting a default view-
def show
#user = User.find(params[:id])
if #user.default_hero.nil?
name = params[:q]
else
name = #user.default_hero.name
end
Thanks for your guys' time and attention if you can point me in the right direction in how to solve this I would ppreciated.
Your show controller action doesn't make much sense. You are setting a local variable (which won't be accessible in the view) if #user.default_hero.nil?. This doesn't accomplish anything and #user.default_hero will still be nil in the view.
That being said, to get rid of your error you can simply do this:
<%= text_field_tag "name", #user.default_hero.nil? ? '' : #user.default_hero.name %>
Based on your comment I would does something like this:
Model
class User < ActiveRecord::Base
has_many :heros
def set_default_hero(name)
hero = self.heros.find_by_name(name) # check if the hero exists already
hero = self.heros.build(:name => name) if hero.nil? # new object if not
hero.default = true # set it as default
hero.save
end
end
Controller:
def default_hero
#user = User.find(params[:id])
#user.set_default_hero(params[:name])
redirect_to #user
end
def show
#user = User.find(params[:id])
#default_hero = #user.default_hero.nil? ? '' : #user.default_hero.name
end
View:
<%= text_field_tag "name", #default_hero %>
You ignored my question about params[:q], so I don't know what to do with that.