在路由中访问APP_CONFIG ['var']?或提供带变量的路线?

Rub*_*tic 6 variables routes ruby-on-rails

我需要在rails 4中提供一些ip地址来设置某些路由的约束.有没有办法从配置文件中获取此数据而不将其编码到路由文件中?

我使用yaml文件和初始化程序为app变量,如:

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

所以我通常可以这样做:

  constraints(:ip => %w[APP_CONFIG['app_url']]) do
    .. my routes..
  end 
Run Code Online (Sandbox Code Playgroud)

这在routes.rb中是否有办法解决这个问题?

Yul*_*ule 0

看一下rails的初始化过程(http://guides.rubyonrails.org/initialization.html)。您会发现路由实际上加载得很早(并且早于 application.rb 或其他初始化程序)。因此它尚未加载该文件。

解决这个问题的方法是将其放入 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__))
Run Code Online (Sandbox Code Playgroud)