动态获取路径路径

Ser*_*sev 5 ruby ruby-on-rails ruby-on-rails-3

我最近将一些模板从ERB转换为Haml.它大多变得更清洁,更好,但按钮定义开始变得很糟糕.

我想转换它

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

这样的事情

= new_button Intern
Run Code Online (Sandbox Code Playgroud)

我还有其他几个实体,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
Run Code Online (Sandbox Code Playgroud)

它按预期工作.我只是不确定那个eval电话(因为它是邪恶的,所有这一切).有一种更简单,更不邪恶的方式吗?

Ser*_*sev 6

哦,这是一个更好的版本:

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
Run Code Online (Sandbox Code Playgroud)


Rya*_*IRL 1

您可能有兴趣查看PolymorphicRouteshttp://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
Run Code Online (Sandbox Code Playgroud)