問題描述
在自定義生成器中生成嵌套路由 (Generating nested routes in a custom generator)
I'm building a generator in rails that generates a frontend and admin controller then adds the routes to the routes file. I can get the frontend working with this:
m.route_resources controller_file_name
but I can't figure out how to do the same for the nested admin route (admin/controller_file_name). Anyone know how to generate these routes?
參考解法
方法 1:
Looking at the code for route_resources
, it doesn't look like it will do anything beyond a bog-standard map.resources :foos
.
Instead, let's write our own method to deal with this issue, based on the original
def route_namespaced_resources(namespace, *resources)
resource_list = resources.map { |r| r.to_sym.inspect }.join(', ')
sentinel = 'ActionController::Routing::Routes.draw do |map|'
logger.route "#{namespace}.resources #{resource_list}"
unless options[:pretend]
gsub_file 'config/routes.rb', /(#{Regexp.escape(sentinel)})/mi do |match|
"#{match}\n map.namespace(:#{namespace}) do |#{namespace}|\n #{namespace}.resources #{resource_list}\n end\n"
end
end
end
We can start this off as a local method in your generator, which you can now call with:
m.route_namespaced_resources :admin, controller_file_name
(by Codebeef、austinfromboston)