重新加载使用rails继承生成的常量

时间:2016-08-17 09:03:35

标签: ruby-on-rails ruby inheritance

我关注轨道中常量的实现。更具体地说,使用由继承的method

填充的常量

编辑:这种担忧与开发模式有关,而非生产。

以下是代码:

# helpers/my_active_code/formatter.rb
module MyActiveCode
  class Formatter
    FORMATTER_MAPPING = ActiveSupport::HashWithIndifferentAccess.new # just a constant
    # Will store something like : 
    # { 
    #    "String" => ::MyActiveCode::Transforms::String,
    #    "Boolean" => ::MyActiveCode::Transforms::Boolean,
    # }
  end
end

# helpers/my_active_code/transforms/object.rb
module MyActiveCode::Transforms
  class Object
    # A superclass that implement an inherited method which store into the constant
    private
    def self.inherited(subclass)
      ActiveRecordViewRewrite::Formatter::FORMATTER_MAPPING.store(identifier, subclass)
    end
  end
end

# helpers/my_active_code/transforms/string.rb
module MyActiveCode::Transforms
  class String
  end
end

我还有一个初始化程序,需要将所有文件放入文件夹helpers / my_active_code / transforms。

当我启动rails控制台时,一切正常,FORMATTER_MAPPING常量已经很好地填充。

然而,在重新加载(重新加载!)之后,FORMATTER_MAPPING常量为空({})。

由于此处描述的常量重新加载,这是完全正常的:http://guides.rubyonrails.org/autoloading_and_reloading_constants.html#constant-reloading

所以我尝试将所有变换文件重新加载到文件helpers / my_active_code / formatter.rb末尾的(helpers / my_active_code / transforms)中,但它不起作用。

我怎样才能解决这个问题并始终将其填充?

0 个答案:

没有答案