Rails帮助用户图片

时间:2011-03-22 19:15:42

标签: ruby-on-rails helpers

我目前在部分内容中有一些脏代码,并且认为将它移动到Helper会很好,但却无法实现。

到目前为止,这是我在“user_picture”部分中的内容:

<% 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 %>

如何让它成为帮助者?

谢谢!

3 个答案:

答案 0 :(得分:1)

将您的代码移至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

然后根据您的观点致电:my_helper(current_user, size)

答案 1 :(得分:0)

在我的头顶,助手可能是:

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

你可以在部分中做这样的事情:

if defined?(user)
  picture_for(user)
elsif logged_in_user
  picture_for(logged_in_user)
else
  picture_for(nil)
end

答案 2 :(得分:0)

我假设您事先知道了尺寸,但您也可以轻松地将其传递给帮手。

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

像这样使用它:(如果logged_in_user为零则确定)

user_picture_tag(logged_in_user)
# OR
user_picture_tag(@user)