refactoring - Rails helper methods with conditional parameters -


sometimes in rails views, have duplicated code, because have set parameters of rails helper method according conditions. like:

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

or 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 way of writing in more elegant way (without repeating whole helper)?

thanks

you can isolate differences in options hash , merge differences shared base options hash:

<%   link_options =      if       {}     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, same sort of thing in own, custom helper method. using helper method preferable because have method can tested, re-used, named (in self-documenting manner), etc.


Comments

Popular posts from this blog

PySide and Qt Properties: Connecting signals from Python to QML -

c# - DevExpress.Wpf.Grid.InfiniteGridSizeException was unhandled -

scala - 'wrong top statement declaration' when using slick in IntelliJ -