Max Ivak
Max Ivak

Reputation: 1549

Rails. Extend link_to helper

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.

Upvotes: 1

Views: 747

Answers (1)

AmShaegar
AmShaegar

Reputation: 1539

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

Upvotes: 0

Related Questions