在 Rails 4 中创建到外部 URL 的 Rails 路由 [英] Creating a rails route to an external URL in Rails 4

查看:40
本文介绍了在 Rails 4 中创建到外部 URL 的 Rails 路由的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一堆路由(~50)需要映射到外部 URL.我绝对可以按照此处中的建议进行操作,但这会造成混乱我的 routes.rb 文件.有什么办法可以将它们放在配置文件中并从我的 routes.rb 文件中引用它?

I have bunch of routes( ~50)which needs to be mapped to external URL. I can do definitely as suggested in here but that will clutter my routes.rb file. Is there any way I can have them in an config file and refer to it from my routes.rb file?

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

Also, when mapping to external URL, if it non production environment, it needs to be mapped to "http:example-test.com/.." and in production mode it needs to be mapped to "http:example.com/...". I know I can have a yml file in config which deals with differnt environments. But how do I access it in my routes.rb file?

推荐答案

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

First let's create a custom configuration variable for the external host:

# config/application.rb
module MyApp
  class Application < Rails::Application
    config.external_host = ENV["EXTERNAL_HOST"]
  end
end

然后让我们根据环境进行设置:

And then lets set it up per environment:

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

这篇关于在 Rails 4 中创建到外部 URL 的 Rails 路由的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆