use*_*057 3 ruby-on-rails ruby-on-rails-4
我有一堆路由(~50)需要映射到外部URL.我绝对可以按照这里的建议做,但这会混乱我的routes.rb文件.有什么办法可以在配置文件中使用它们并从我的routes.rb文件中引用它吗?
此外,当映射到外部URL时,如果它是非生产环境,则需要将其映射到"http:example-test.com/ ..",并且在生产模式下,它需要映射到"http:example.com/. ..".我知道我可以在配置中有一个yml文件来处理不同的环境.但是如何在routes.rb文件中访问它?
首先,让我们为外部主机创建一个自定义配置变量:
# config/application.rb
module MyApp
class Application < Rails::Application
config.external_host = ENV["EXTERNAL_HOST"]
end
end
Run Code Online (Sandbox Code Playgroud)
然后让我们根据环境进行设置:
# config/environments/development.rb
Rails.application.configure do
# ...
config.external_host ||= 'dev.example.com'
end
# config/environments/test.rb
Rails.application.configure do
# ...
config.external_host ||= 'test.example.com'
end
# config/environments/production.rb
Rails.application.configure do
# ...
config.external_host ||= 'example.com'
end
Run Code Online (Sandbox Code Playgroud)
然后我们设置路线:
Rails.application.routes.draw do
# External urls
scope host: Rails.configuration.external_host do
get 'thing' => 'dev#null', as: :thing
end
end
Run Code Online (Sandbox Code Playgroud)
让我们尝试一下:
$ rake routes
Prefix Verb URI Pattern Controller#Action
thing GET /thing(.:format) dev#null {:host=>"dev.example.com"}
$ rake routes RAILS_ENV=test
Prefix Verb URI Pattern Controller#Action
thing GET /thing(.:format) dev#null {:host=>"test.example.com"}
$ rake routes RAILS_ENV=production
Prefix Verb URI Pattern Controller#Action
thing GET /thing(.:format) dev#null {:host=>"example.com"}
$ rake routes EXTERNAL_HOST=foobar
Prefix Verb URI Pattern Controller#Action
thing GET /thing(.:format) dev#null {:host=>"foobar"}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
736 次 |
| 最近记录: |