4

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.

Zachary Schuessler
  • 3,644
  • 2
  • 28
  • 43
jwall
  • 759
  • 1
  • 8
  • 17

2 Answers2

5

To have code run before Rails itself is loaded, put it above require 'rails/all' in config/application.rb.

DanS
  • 17,550
  • 9
  • 53
  • 47
  • Thank you for your answer, I tried with global scope `::` but it does not work. The problem is that, when Rails generates class `User`, class `AppConstant` isn't initialized. But I don't know how to make class `AppConstant` get initialized before it reads `User` class – jwall May 22 '12 at 02:11
  • You are right, finally I have to do this way to solve the problem. – jwall May 23 '12 at 01:08
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
Kris
  • 19,188
  • 9
  • 91
  • 111