Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating a rails route to an external URL in Rails 4

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?

like image 933
user2452057 Avatar asked Oct 16 '25 06:10

user2452057


2 Answers

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"}
like image 200
max Avatar answered Oct 17 '25 19:10

max


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"
like image 23
sushilprj Avatar answered Oct 17 '25 21:10

sushilprj