Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Access APP_CONFIG['var'] inside routes? or supply routes with variables?

I need to do in rails 4 supply some ip address to set a constraint on certain routes. Is there a way to get this data from a config file without harcoding it into the routes file?

Im using a yaml file and initializer for app variables like:

APP_CONFIG = YAML.load_file("#{Rails.root}/config/application.yml")[Rails.env]

so normally I could do:

  constraints(:ip => %w[APP_CONFIG['app_url']]) do
    .. my routes..
  end 

This fails in the routes.rb is there a way to fix this?

like image 360
Rubytastic Avatar asked Apr 23 '15 09:04

Rubytastic


1 Answers

The routes.rb file is a ruby file which is instantiated once, and loaded into memory.

You can just add the ruby code inside it and it will be executed once:

Rails.application.routes.draw do
  app_config = YAML.load_file("#{Rails.root}/config/application.yml")[Rails.env]
  constraints(:ip => %w[app_config['app_url']]) do
    .. my routes..
  end 
end

This will instantiate the routes.rb file with the variable loaded from the yml and available throughout your rails routes app. You don't even need to use a env variable. Local variable seems a better idea.

You can also put logic inside and make it environment dependant:

if Rails.env.production?
  app_config = YAML.load_file("#{Rails.root}/config/application.yml")[Rails.env]
  constraints(:ip => %w[app_config['app_url']]) do
    .. my routes..
  end
else
   .. my routes ...
end
like image 143
Jorge de los Santos Avatar answered Oct 19 '22 23:10

Jorge de los Santos