在Rails中扩展ActiveRecord :: Base在测试环境中不起作用

时间:2009-09-28 00:12:18

标签: ruby-on-rails activerecord module

当我在environments.rb中添加以下代码块时,ActiveRecord :: Base在开发环境中扩展模块,但不在测试环境中扩展。

require "active_record_patch"
ActiveRecord::Base.send(:extend, ModelExtensions)

包含该模块的库文件如下:

module ModelExtensions

  def human_name_for(attr_hash)
     # do something
  end

end

在开发环境中加载./script/server和./script/console似乎很好。但是在测试环境中,会发生以下错误:

/home/test/rails_app/vendor/rails/activerecord/lib/active_record/base.rb:1959:in `method_missing':NoMethodError: undefined method `human_name_for' for #<Class:0x4a8d33>

2 个答案:

答案 0 :(得分:1)

对于解决方案,我修改了模块并将模块包含在lib文件本身的ActiveRecord :: Base中:

module HumanAttributes

  module ClassMethods

    def human_name_for(attr_hash)
      unless attr_hash.nil?
        @@human_names = attr_hash

        class << self
          def human_attribute_name key
            @@human_names[key.to_sym] || super unless key.nil?
          end
        end
      end
    end

  end

end

module ActiveRecord
  class Base
    extend HumanAttributes::ClassMethods
  end
end

这使得human_name_for可以在所有环境中从ActiveRecord :: Base扩展的任何类访问。

请记住要求模型文件顶部的文件。

答案 1 :(得分:0)

这适合我。

module ModelExtensions

  def human_name_for(attr_hash)
     # do something
  end

end

在environment.rb

include ModelExtensions
ActiveRecord.extend(ModelExtensions) 

然后这适用于ArObject.human_name _for(:asd)