Search code examples
ruby-on-railsrubymethodslink-tohelpermethods

Rails helper method with link_to options as optionals


I'm trying to create a helper method that can have optional arguments for link_to method. My intention is to create a helper method for different cases:

# Typical case #1 (can have any number of extra arguments)
<%= toolbar_item('google.com', 'Google', 'globe', 'btn-primary', target: '_blank') %>

# Typical case #2 (extra arguments are optional)
<%= toolbar_item(root_path, 'Start', 'flag', 'btn-primary') %>

Follows the code:

def toolbar_item(url,text,icon,custom_class, optional_extra_settings = {})
  link_to raw("<i class='fa fa-#{icon}'></i> #{text}"), url, class: custom_class, optional_extra_settings
end

It's no good. link_to method does not recognize the extra_settings and raises and error.

Any ideas? Thanks!


Solution

  • The link_to method accepts only 3 arguments. The last argument needs to be a hash. Therefore you have to merge your class setting with the optional extra settings hash.

    Change your example to:

    def toolbar_item(url, text, icon, custom_class, optional_extra_settings = {})
      html_options = { class: custom_class }.merge(optional_extra_settings)
      link_to raw("<i class='fa fa-#{h icon}'></i> #{h text}"), url, html_options
    end
    

    Furthermore, you will notice that I used h to escape your icon and text. Just to be safe, because you disabled the auto-escaping that is usually done by Rails by using raw.