4

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.

Galaxy
  • 3,370
  • 3
  • 29
  • 41
  • So in your example, are you looking to have it override the default class of 'pjax' or add the 'current' class to the 'pjax' class (eg: 'current pjax')? – Preacher Dec 23 '11 at 01:43

3 Answers3

6
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:

  • link_to_pjax 'click me', my_super_path, class: 'ahah', id: 'hello'
  • link_to_pjax 'click me', my_super_path
  • etc

My bad...

Damien
  • 26,933
  • 7
  • 39
  • 40
1

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
Chris
  • 2,744
  • 3
  • 24
  • 39
1
def link_to_pjax(name, path, options={})
  default_options = { :class => "pjax" }
  link_to(name, path, options.merge(default_options))
end
Federico Builes
  • 4,939
  • 4
  • 34
  • 48