Rails: Run initializer before creating classes

只谈情不闲聊 提交于 2019-12-11 01:17:43

问题


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

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!