Given t开发者_如何学运维he following routes.rb file:
# Add Admin section routes
map.namespace :admin do |admin|
admin.resources :admin_users
admin.resources :admin_user_sessions, :as => :sessions
admin.resources :dashboard
# Authentication Elements
admin.login '/login', :controller => 'admin_user_sessions', :action => 'new'
admin.logout '/logout', :controller => 'admin_user_sessions', :action => 'destroy'
# Default is login page for admin_users
admin.root :controller => 'admin_user_sessions', :action => 'new'
end
Is it possible to alias the 'admin' section to something else without having to change every redirection and link_to in the application? The main reason is that it's something I'd like to be configurable on the fly and hopefully make it also a bit less easy to guess.
map.namespace
method just sets some common options for routes inside its block. It uses with_options
method:
# File actionpack/lib/action_controller/routing/route_set.rb, line 47
def namespace(name, options = {}, &block)
if options[:namespace]
with_options({:path_prefix => "#{options.delete(:path_prefix)}/#{name}", :name_prefix => "#{options.delete(:name_prefix)}#{name}_", :namespace => "#{options.delete(:namespace)}#{name}/" }.merge(options), &block)
else
with_options({:path_prefix => name, :name_prefix => "#{name}_", :namespace => "#{name}/" }.merge(options), &block)
end
end
So it is possible to use with_options
method directly instead of namespace
:
map.with_options(:path_prefix => "yournewprefix", :name_prefix => "admin_", :namespace => "admin/" ) do |admin|
admin.resources :admin_users
# ....
end
And you can continue to use routes the same way as before, but prefix will be "yournewprefix" instead of "admin"
admin_admin_users_path #=> /yournewprefix/admin_users
In order to create an alias to the namespace (calling one api_version
for example, from another router address) you can do the following:
#routes.rb
%w(v1 v2).each do |api_version|
namespace api_version, api_version: api_version, module: :v1 do
resources :some_resource
#...
end
end
this will cause the routes /v1/some_resource
and /v2/some_resource
to get to the same controller. then you can use params[:api_version]
to get the evrsion you need and respond accordingly.
Like in any other resource, :path seem to be working fine for me.
namespace :admin, :path => "myspace" do
resources : notice
resources :article do
resources :links , :path => "url"
end
end
end
精彩评论