Reputation: 3400
I'm trying to hook up a custom helper that has a default class 'pjax' but also retains an ability to add classes where need be.
Example:
link_to_pjax('pagename', page_path, :class => 'current')
So the helper would add the 'pjax' by default, and also the class 'current', or whatever is passed in.
def link_to_pjax(name, path, options = {:class => 'pjax'})
link_to(name, path, options)
end
The syntax is freaking me out. Any advice would be much appreciated.
Upvotes: 4
Views: 2837
Reputation: 2800
I improved Delba answer to handle block version of link_to:
def link_to_pjax(*args, &block)
if block_given?
options = args.first || {}
html_options = args.second
link_to_pjax(capture(&block), options, html_options)
else
name = args[0]
options = args[1] || {}
html_options = args[2] || {}
html_options[:class] ? html_options[:class] += ' pjax' : html_options[:class] = 'pjax'
link_to(name, options, html_options)
end
end
Upvotes: 1
Reputation: 27483
def link_to_pjax(name, path, options)
options[:class] += ' pjax'
link_to(name, path, options)
end
edit
After test, it's much less elegant:
def link_to_pjax(name, path, options = {})
options[:class] ? options[:class] += ' pjax' : options[:class] = 'pjax'
link_to(name, path, options)
end
My first solution works but only if you have still specified a class.
The latest works in all cases:
My bad...
Upvotes: 6
Reputation: 5107
def link_to_pjax(name, path, options={})
default_options = { :class => "pjax" }
link_to(name, path, options.merge(default_options))
end
Upvotes: 1