if语句的逻辑

Ric*_*wis 2 ruby if-statement ruby-on-rails ruby-on-rails-4

在我看来,我有以下逻辑,根据人物档案是否存在,选择要显示的头像图片

 <% if @profile %>
   <%= image_tag(@profile.avatar_url(:thumb)) %>
 <% else %>
   <%= image_tag(default_image_url) %>
 <% end %>
Run Code Online (Sandbox Code Playgroud)

辅助方法

def default_image_url
  hash = Digest::MD5.hexdigest(current_user.email)
  "https://secure.gravatar.com/avatar/#{hash}?s=100&d=mm"
end
Run Code Online (Sandbox Code Playgroud)

当有人没有创建一个配置文件时,这种方法很好,但是当他们这样做并且仍然想要使用他们的gravatar时,这个逻辑会失败,因为我的if条件需要是if

<% if @profile.avatar? %>
   <%= image_tag(@profile.avatar_url(:thumb)) %>
 <% else %>
   <%= image_tag(default_image_url) %>
 <% end %>
Run Code Online (Sandbox Code Playgroud)

在创建没有用户上传图像的配置文件时,根本没有显示图像.

我如何涵盖所有场景

任何帮助赞赏

编辑

我正在尝试

<% unless @profile || @profile.avatar %>
Run Code Online (Sandbox Code Playgroud)

谢谢

mde*_*tis 5

从@ ArieShaw的答案开始的一些重构:

帮手

def profile_image_url
  @profile.try(:avatar?) ? @profile.avatar_url(:thumb) : default_image_url
end
Run Code Online (Sandbox Code Playgroud)

视图

<%= image_tag profile_image_url %>
Run Code Online (Sandbox Code Playgroud)