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

I need to do in rails 4, put some ip address to set a restriction on certain routes. Is there a way to get this data from the configuration file without attaching it to the routes file?

Im uses the yaml file and initializer for application variables, for example:

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

so that I could normally:

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

This fails in route.rb, is there any way to fix this?

+5
source share
3 answers

The routes.rb is a ruby ​​file that is created once and loaded into memory.

You can simply add ruby ​​code to 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 create an instance of the routes.rb file with the variable loaded from yml and available in your rails routes application. You do not even need to use the env variable. A local variable seems like a better idea.

You can also put the logic inside and make it environment dependent:

 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 
+1
source

A look at the rail initialization process ( http://guides.rubyonrails.org/initialization.html ). You will see that routing is loaded quite early (and earlier than application.rb or other initializers). Therefore, he has not yet uploaded this file.

Be that as it may, put this in your boot.rb:

 # Set up gems listed in the Gemfile. ENV['BUNDLE_GEMFILE'] ||= File.expand_path('../../Gemfile', __FILE__) require 'bundler/setup' if File.exist?(ENV['BUNDLE_GEMFILE']) #Now load app config: require 'yaml' APP_CONFIG = YAML.load_file(File.expand_path('../../config/application.yml', __FILE__)) 
0
source

I believe that you are facing a boot order problem. Perhaps you could hack this, but ...

I highly recommend using Figaro to solve this problem. This is a gem specifically designed for rail configuration and will work well with 12 application deployments (like Heroku): https://github.com/laserlemon/figaro

I use Figaro in the application I'm working on now, and was able to confirm access to env variables in the routes file. I believe that this stone will solve your current problem and other configuration problems that you do not even know about.

0
source

All Articles