Rails Helper for user picture
I currently have some dirty code in a partial and thought it'd be good to move it to a Helper but can't make it happen.
Here is what I have in my "user_picture" partial so far:
<% if defined?(user) %>
<%- if user.picture_id == 0 -%>
<%= image_tag('/images/einstein.png', :size => size) -%>
<%- else -%>
<%= image_tag(user.picture.public_filename(:avatar), :size => size) %>
<%- end -%>
<% else %>
<%- if !logged_in_user || logged_in_user.picture_id == 0 -%>
<%= image_tag('/images/einstein.png', :size => size) -%>
<%- else -%>
<%= image_tag(logged_in_user.picture.public_开发者_开发知识库filename(:avatar), :size => size) %>
<%- end -%>
<% end %>
How do I make it a helper?
Thanks!
remove your code to app/helpers/application_helper.rb
def my_helper(user, size)
if defined?(user)
if user.picture_id == 0
image_tag('/images/einstein.png', :size => size)
else
image_tag(user.picture.public_filename(:avatar), :size => size)
end
else
if !logged_in_user || logged_in_user.picture_id == 0
image_tag('/images/einstein.png', :size => size)
else
image_tag(logged_in_user.picture.public_filename(:avatar), :size => size) %>
end
end
end
and then call from your views: my_helper(current_user, size)
Off the top of my head, the helper could be:
def picture_for(user) #If you need to, pass size as a parameter or..
if user.nil? or user.picture.nil?
image_tag('/images/einstein.png', :size => size) # ..you need to define size somewhere in this helper
else
image_tag user.picture.public_filename(:avatar), :size => size
end
end
And you could do something like this in the partial:
if defined?(user)
picture_for(user)
elsif logged_in_user
picture_for(logged_in_user)
else
picture_for(nil)
end
I'm assuming you know the size in advance, but you could easily pass that into the helper as well.
def user_picture_tag(user)
return image_tag(user.picture.public_filename(:avatar), :size => "50x50") if user.present? && user.picture_id != 0
image_tag('/images/einstein.png', :size => "50x50")
end
Use it like this: (its ok if logged_in_user
is nil)
user_picture_tag(logged_in_user)
# OR
user_picture_tag(@user)
精彩评论