如何解决Rails将路线列表作为带有参数的路径
我想获得我的Rails应用程序支持的URL列表,但是我不想提前提供任何参数。
例如,我想将user_registration_path
的路径列出为/%{locale}/users/sign_up
。
我可以像这样获得命名路由的列表(在Rails控制台中进行测试):
Rails.application.routes.named_routes.helper_names
示例输出:
["rails_info_properties_path","rails_info_routes_path","rails_info_path","rails_mailers_path","rails_service_blob_path","rails_blob_path","rails_blob_representation_path","rails_representation_path","rails_disk_service_path"...]
在Rails中有什么方法可以实现这一目标吗?
解决方法
您可以通过使用rails routes
命令查看dumps the routes的导轨来实现此目的。
# frozen_string_literal: true
require "rails/command"
module Rails
module Command
class RoutesCommand < Base # :nodoc:
class_option :controller,aliases: "-c",desc: "Filter by a specific controller,e.g. PostsController or Admin::PostsController."
class_option :grep,aliases: "-g",desc: "Grep routes by a specific pattern."
class_option :expanded,type: :boolean,aliases: "-E",desc: "Print routes expanded vertically with parts explained."
def perform(*)
require_application_and_environment!
require "action_dispatch/routing/inspector"
say inspector.format(formatter,routes_filter)
end
private
def inspector
ActionDispatch::Routing::RoutesInspector.new(Rails.application.routes.routes)
end
def formatter
if options.key?("expanded")
ActionDispatch::Routing::ConsoleFormatter::Expanded.new
else
ActionDispatch::Routing::ConsoleFormatter::Sheet.new
end
end
def routes_filter
options.symbolize_keys.slice(:controller,:grep)
end
end
end
end
这里的关键是:
inspector.format(formatter,routes_filter)
格式化程序实际上只是一个对section
,header
和result
做出响应的类:
# formats routes as a simple array of hashes
class HashFormatter
def initialize
@buffer = []
end
# called for the main routes and also for each
# mounted engine
def section(routes)
routes.each do |r|
@buffer << r.slice(:name,:verb,:path)
end
end
# this method does not need to do anything since the "headers" are
# part of the hashes
def header(routes)
end
def result
@buffer
end
end
然后我们可以使用以下命令调用格式化程序:
inspector = ActionDispatch::Routing::RoutesInspector.new(Rails.application.routes)
inspector.format(HashFormatter.new)
并获得一个哈希数组:
[{:name=>"",:verb=>"GET",:path=>"/pizzas/:foo(.:format)"},{:name=>"",:path=>"/pizzas/:foo/:bar(.:format)"},:path=>"/pizzas/:foo/:bar/:baz(.:format)"},{:name=>"foo",:verb=>"DELETE",:path=>"/foo(.:format)"},{:name=>"root",:path=>"/"},#...]
这样做的好处是您可以piggy带现有代码,该代码可以收集所有已安装引擎的路由并拒绝内部路由。
,您可以尝试使用此命令:
Rails.application.routes.routes
.map { |r| { path: r.path.spec.to_s } }
它将为您提供以下输出:
{:path=>"/admin/users/:id/edit(.:format)"},{:path=>"/admin/users/:id(.:format)"},
或者作为一个数组(您可以改进它,这只是一个简单的示例):
Rails.application.routes.routes
.flat_map { |r| r.path.spec.to_s }
.uniq
.map { |path| path.gsub('(.:format)','') }
[
"/admin/users","/admin/users/new","/admin/users/:id/edit","/admin/users/:id"
]
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。