我有一堆路由(〜50条),这些路由需要映射到外部URL。我绝对可以按照here中的建议进行操作,但这会使我的route.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"}

10-07 19:18
查看更多