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?
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
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
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With