Rails:在创建类之前运行初始化程序 [英] Rails: Run initializer before creating classes

查看:55
本文介绍了Rails:在创建类之前运行初始化程序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

基本上我在 RAILS_ROOT/config/initialiers/app_constant.rb 有一个 initializer 类 使一切都易于控制.

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

RAILS_ROOT/model/user.rb 中,我有设置:

class User < ActiveResource::Base
  self.site = AppConstant::APIURL
end

当运行 rails s 时,出现以下错误

And when run rails s, I got the following error

<class:User>: uninitialized constant User::AppConstant::APIURL

我知道问题是因为 Rails 在创建类后运行初始化程序.在 Rails 设置类之前,有没有办法让一些初始化程序运行?

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?

最后通过在加载正确的 application.rb 中添加 require "#{Rails.root}\conf\initializers\app_constant.rb" 解决了这个问题在 Rails 加载模型之前.

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.

推荐答案

要在加载 Rails 之前运行代码,请将其放在 config/application 中的 require 'rails/all' 上方.rb.

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

这篇关于Rails:在创建类之前运行初始化程序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆