Ruby on rails 轨道。将链接扩展到帮助器

Ruby on rails 轨道。将链接扩展到帮助器,ruby-on-rails,link-to,view-helpers,link-to-function,Ruby On Rails,Link To,View Helpers,Link To Function,如何将Rails link_扩展到helper,以添加特定类,而不中断link_到标准功能。 我想让我的自定义助手如下所示: 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]

如何将Rails link_扩展到helper,以添加特定类,而不中断link_到标准功能。 我想让我的自定义助手如下所示:

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
我想保留link_的所有功能,以:

=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>
=my_cool_link_至“链接标题”,产品路径(@product)
# 
=my_cool_link_to'link title',product_path(@product),:class=>'btn'
# 
=my_cool_link_to'link title',product_path(@product),:class=>'btn','data id'=>'123'
# 

等等。

有两种方法可以设置多个html类。可以是以空格分隔的字符串,也可以是数组

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
def my_cool_link_to(name=nil,options=nil,html_options=nil,&block)
html_选项[:类]| |=[]#确保它不是零
如果html\u选项[:类],\u是一个吗?排列

html_options[:class]如果您这样做只是为了添加类,那么创建一个helper方法来添加您的类并使用标准的链接将更加明智
link\u to name,link,class:new\u方法(old\u class)
这个想法是创建一个助手,在用户指定的选项中添加必要的选项(不仅是:class,还有其他选项)。我还想这样写:=my_cool_link_to'link title',product_path(@product),不指定任何类,但它应该向链接添加必要的类。我不认为这回答了最初的问题。