EmFi 是对的。我没有回答这个问题,只是表达了我的看法。
将以下代码放入 Rails 应用程序内的 config initializers 目录中的初始化文件中。您命名文件的名称与框架无关,因为此目录中的所有文件都在加载路径中。我建议您将其称为actioncontroller_resource_monkeypatch.rb,以明确意图。
ActionController::Resources.module_eval do
def map_resource_routes(map, resource, action, route_path, route_name = nil, method = nil, resource_options = {} )
if resource.has_action?(action)
action_options = action_options_for(action, resource, method, resource_options)
formatted_route_path = route_path.match(/\/:format\//) ? route_path : "#{route_path}.:format"
if route_name && @set.named_routes[route_name.to_sym].nil?
map.named_route(route_name, formatted_route_path, action_options)
else
map.connect(formatted_route_path, action_options)
end
end
end
end
我的答案使用与 EmFi 相同的方法,即通过猴子补丁 ActionController::Resources#map_resource_routes。我决定把我的帽子扔进戒指,因为它没有提供完整的实现,这是留给你自己的练习。我也觉得formatted_route_path 的三元赋值比 if-else/unless-else 块更干净、更简洁。多行代码而不是五行!这是我为 200 赏金所能做的最低限度!
现在运行rake routes
new_api_v1_company GET /api/v1/:format/company/new {:action=>"new", :controller=>"api/v1/companies"}
edit_api_v1_company GET /api/v1/:format/company/edit {:action=>"edit", :controller=>"api/v1/companies"}
api_v1_company GET /api/v1/:format/company {:action=>"show", :controller=>"api/v1/companies"}
PUT /api/v1/:format/company {:action=>"update", :controller=>"api/v1/companies"}
DELETE /api/v1/:format/company {:action=>"destroy", :controller=>"api/v1/companies"}
POST /api/v1/:format/company {:action=>"create", :controller=>"api/v1/companies"}
多田!