简体   繁体   中英

Rails helper methods with conditional parameters

Sometimes in my Rails views, I have some duplicated code, because I have to set the parameters of a Rails helper method according to some conditions. Like:

<% if something %>
  <%= link_to "Target", @target, class: "target-a" %>
<% else %>
  <%= link_to "Target", @target, class: "target-b" %>
<% end %>

or another example:

<% if tooltip == false %>
  <%= image_tag picture.url(size), class: "img-responsive #{css_class}" %>
<% else %>
  <%= image_tag picture.url(size), class: "img-responsive #{css_class}", data: { toggle: "tooltip", placement: "bottom" }, title: "#{picture.name}" %>
<% end %>

Is there a way of writing this in a more elegant way (without repeating the whole helper)?

Thanks

You can isolate the differences in the options hash and merge just the differences into a shared base options hash:

<%
  link_options = 
    if something
      {}
    else
      { data: { toggle: "tooltip", placement: "bottom" }, title: "#{picture.name}" }
    end
%>
<%= image_tag picture.url(size), 
              link_options.merge(class: "img-responsive #{css_class}") %>

Or, better yet, you could do the same sort of thing but in your own, custom helper method. Using a helper method is preferable because then you have a method that can be tested, re-used, named (in a self-documenting manner), etc.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM