ActiveRecord :: Base in Rails extension does not work in test environment

When I add the following code to environment.rb, ActiveRecord :: Base extends the module in the development environment, but not in the test environment.

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

      

The library file containing the module looks like this:

module ModelExtensions

  def human_name_for(attr_hash)
     # do something
  end

end

      

Loading. / Script / server and. / script / console looks great in a development environment. But in a test environment, the following error occurs:

/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


source to share


2 answers


For a solution, I modified the module and included the module in ActiveRecord :: Base in the lib file itself:

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

      



This makes human_name_for available to any class from ActiveRecord :: Base in all environments.

Don't forget to include the file at the top of the model file.

+1


source


This works for me.

module ModelExtensions

  def human_name_for(attr_hash)
     # do something
  end

end

      

In environment.rb



include ModelExtensions
ActiveRecord.extend(ModelExtensions) 

      

Then this works ArObject.human_name _for (: asd)

0


source







All Articles