简体   繁体   English

在Ruby on Rails中访问给定路径的控制器命令

[英]Accessing Controller Command Given a Path in Ruby on Rails

In Ruby on Rails is there a way to get a string of the contoller command corresponding to a given path? 在Ruby on Rails中,有没有一种方法来获取与给定路径相对应的contoller命令的字符串? For example, given route 例如,给定路线

  get 'add_address' => 'locations#new'

The code: 编码:

puts add_address_path.some_method

Would output 将输出

'locations#new'

Routes are pretty well encapsulated in the routes file, and I'm not sure how you would go about sending a message to an object named after the route to extract the controller and action. 路由已很好地封装在路由文件中,我不确定如何将消息发送到以路由命名的对象以提取控制器和动作。

If you're open to an alternative, you could try prying it out with something like this: 如果您愿意使用其他方法,则可以尝试使用以下方法撬开它:

class MyRouteParser < Struct.new(:named_route)

  include Rails.application.routes.url_helpers

  def controller
    @parsed[:controller]
  end

  def action
    @parsed[:action]
  end

  def controller_with_action
    "#{controller}\##{action}"
  end

  private

  def parse
    @parsed ||= Rails.application.routes.recognize_path(named_route)
  end
end

This would provide the string you want with: 这将提供您想要的字符串:

route = MyRouteParser.new("add_address_path")
route.controller_with_action

"locations#new"

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM