1

How to extend Rails link_to helper to add a specific class and not to break link_to standard functionality. I want to have my custom helper like this:

module MyModule
  module MyHelper

    def my_cool_link_to(body, url_options, html_options)
      # here add 'myclass' to existing classes in html_options
      # ?? html_options[:class] || = 


      link_to body, url_options, html_options
    end
  end
end

I want to remain all the functionality of link_to:

=my_cool_link_to 'Link title', product_path(@product)
# <a href=".." class="myclass">Link title</a>

=my_cool_link_to 'Link title', product_path(@product), :class=>'btn'
# <a href=".." class="btn myclass">Link title</a>

=my_cool_link_to 'Link title', product_path(@product), :class=>'btn', 'data-id'=>'123'
# <a href=".." data-id="123" class="btn myclass">Link title</a>

etc.

Max Ivak
  • 1,529
  • 17
  • 39
  • If you're doing this simply to add classes, then perhaps it would be wiser to create a helper method to add your classes and use the standard link_to. `link_to name, link, class: new_method(old_class)` – SHS Dec 14 '14 at 02:31
  • the idea is creating a helper that adds necessary options (not only :class, but also other options) to options specified by user. Also I want to write like this: =my_cool_link_to 'Link title', product_path(@product), without specifiying any class, but it should add necessary classes to the link. – Max Ivak Dec 14 '14 at 14:21

1 Answers1

0

There are two ways you can set multiple html classes. Either as String separated by space or as an Array.

def my_cool_link_to(name = nil, options = nil, html_options = nil, &block)
  html_options[:class] ||= []                    # ensure it's not nil
  if html_options[:class].is_a? Array
    html_options[:class] << 'your-class'         # append as element to array
  else
    html_options[:class] << ' your-class'        # append with leading space to string
  end

  link_to(name, options, html_options, block)    # call original link_to
end
AmShaegar
  • 1,491
  • 9
  • 18