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?
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
Then we setup the route:
Rails.application.routes.draw do
# External urls
scope host: Rails.configuration.external_host do
get 'thing' => 'dev#null', as: :thing
end
end
And lets try it out:
$ 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"}
Try this. Hope this will work for you ..
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"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With