Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get route path dynamically

I recently converted some of my templates from ERB to Haml. Mostly it became cleaner and nicer, but button definitions started to suck.

I want to convert this

= link_to t('.new', :default => t("helpers.links.new")),
          new_intern_path,                                       
          :class => 'btn btn-primary' if can? :create, Intern    

to something like this

= new_button Intern

I have several other entities besides Intern so all other pages would benefit from this as well.

So, I typed this code

  def new_button(person_class)
    return unless can?(:create, person_class)

    new_route_method = eval("new_#{person_class.name.tableize}_path")

    link_to t('.new', :default => t("helpers.links.new")),
              new_route_method,                                       
              :class => 'btn btn-primary'
  end

It's working as expected. I'm just not sure about that eval call (because it's evil and all that). Is there a simpler and less evil way?

like image 738
Sergio Tulentsev Avatar asked Jun 19 '12 17:06

Sergio Tulentsev


2 Answers

Oh, here's a better version:

def edit_button(person)
  return unless can?(:edit, person)

  link_to t('.edit', :default => t("helpers.links.edit")),
          send("edit_#{person.class.name.singularize.underscore}_path", person),
          :class => 'btn btn-mini'
end
like image 103
Sergio Tulentsev Avatar answered Nov 16 '22 22:11

Sergio Tulentsev


You may be interested in taking a look at PolymorphicRoutes (http://api.rubyonrails.org/classes/ActionDispatch/Routing/PolymorphicRoutes.html#method-i-polymorphic_path).

With it, your code could look something like:

def edit_button(person)
  return unless can?(:edit, person)

  link_to t('.edit', :default => t("helpers.links.edit")),
          edit_polymorphic_path(person),
          :class => 'btn btn-mini'
end
like image 23
Ryan_IRL Avatar answered Nov 17 '22 00:11

Ryan_IRL