问题
Basically I have an initializer class
at RAILS_ROOT/config/initialiers/app_constant.rb
to make everything easy to control.
class AppConstant
APIURL = 'http://path.to.api'
end
And in the RAILS_ROOT/model/user.rb
, I have the settings:
class User < ActiveResource::Base
self.site = AppConstant::APIURL
end
And when run rails s
, I got the following error
<class:User>: uninitialized constant User::AppConstant::APIURL
I know that the problem is because Rails run Initializers after creating the Classes. Is there any way to make some Initializers run before Rails setup it classes?
Finally this problem is solved by adding require "#{Rails.root}\conf\initializers\app_constant.rb"
to the application.rb
which is loaded right before Rails loads models.
回答1:
To have code run before Rails itself is loaded, put it above require 'rails/all'
in config/application.rb
.
回答2:
Another solution would be to wrap the constant in a method so it is not evaluated when the class is loaded, but only later when the method is called:
def self.site
AppConstant::APIURL
end
If it needs to be settable as well:
def self.site=(url)
@site = url
end
def self.site
@site ||= AppConstant::APIURL
end
来源:https://stackoverflow.com/questions/10683666/rails-run-initializer-before-creating-classes