views:

627

answers:

2

When I add the following block of code in environments.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 which contains the module is as follows:

module ModelExtensions

  def human_name_for(attr_hash)
     # do something
  end

end

Loading ./script/server and ./script/console seems fine on the development environment. But on the 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>
+1  A: 

For the solution, I modified the module and included the module to ActiveRecord::Base on 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 accessible by any class extending from ActiveRecord::Base on all environments.

Just remember to require the file on the top of model file.

Ken Ming Ong
A: 

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)

Anders B