Galaxy
Galaxy

Reputation: 3400

Rails 3 - Custom link_to helper (with default class and ability to add classes)

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

Answers (3)

Chris
Chris

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

Damien
Damien

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:

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

My bad...

Upvotes: 6

Federico Builes
Federico Builes

Reputation: 5107

def link_to_pjax(name, path, options={})
  default_options = { :class => "pjax" }
  link_to(name, path, options.merge(default_options))
end

Upvotes: 1

Related Questions