Get route route dynamically

I recently converted some of my templates from ERB to Haml. It basically got cleaner and more enjoyable, 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 objects besides Intern, so all other pages will also benefit from this.

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 works as expected. I'm just not sure about this call eval(because it is evil and all that). Is there a simpler and less evil way?

+5
source share
2 answers

PolymorphicRoutes (http://api.rubyonrails.org/classes/ActionDispatch/Routing/PolymorphicRoutes.html#method-i-polymorphic_path).

:

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
+1

, :

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

All Articles