我有一堆路由(~50)需要映射到外部 URL。我绝对可以按照建议做here https://stackoverflow.com/questions/3622706/creating-a-rails-route-to-an-external-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
然后让我们根据环境进行设置:
# 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
然后我们设置路线:
Rails.application.routes.draw do
# External urls
scope host: Rails.configuration.external_host do
get 'thing' => 'dev#null', as: :thing
end
end
让我们尝试一下:
$ 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"}
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)