动态获取路径路径
我最近将一些模板从ERB转换为Haml。 它大多变得更干净,更好,但按钮定义开始变得很糟糕。
我想转换它
= link_to t('.new', :default => t("helpers.links.new")), new_intern_path, :class => 'btn btn-primary' if can? :create, Intern
这样的事情
= new_button Intern
除了Intern
,我还有其他几个实体,所以其他所有页面也会从中受益。
所以,我输入了这段代码
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
它按预期工作。 我只是不确定那个eval
电话(因为它是邪恶的,所有这一切)。 是否有更简单,更不邪恶的方式?
您可能有兴趣看一下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
哦,这是一个更好的版本:
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