在Rails 4

时间:2015-10-12 13:37:35

标签: ruby-on-rails ruby-on-rails-4

我有一堆需要映射到外部URL的路由(~50)。我可以按here中的建议明确地做,但这会使我的routes.rb文件混乱。有什么办法可以在配置文件中使用它们并从我的routes.rb文件中引用它吗?

此外,当映射到外部URL时,如果它是非生产环境,则需要映射到“http:example-test.com/ ..”,并且在生产模式下,它需要映射到“http:example。 COM / ...“。我知道我可以在配置中有一个yml文件来处理不同的环境。但是如何在routes.rb文件中访问它?

2 个答案:

答案 0 :(得分:8)

首先,让我们为外部主机创建一个自定义配置变量:

# 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"}

答案 1 :(得分:3)

试试这个。希望这对你有用..

MyApp::Application.routes.draw do
  # External urls
  scope host: 'www.example.com' do
    get 'thing' => 'dev#null', as: :thing
  end
end

# Use thing_url in your veiws (thing_path would not include the host)
# thing_url => "http://www.example.com/thing"