0

Im trying to extend a InstanceMethods of a gem (Globalize)

module Globalize
  module ActiveRecord
    module InstanceMethods 
      def foo
        puts "Bar!"
      end
    end
  end
end

However, this overwrites the existing instance methods of Globalize.

What is the correct way of giving a previously declared module additional instance methods?

Update: Trying to require them doesnt seem to work either:

module Globalize
  require 'globalize'
  module ActiveRecord
    require 'globalize/active_record'
    module InstanceMethods
      require 'globalize/active_record/instance_methods'
      def foo
        puts "Bar!"
      end
    end
  end
end

Update: By using answer provided by roxxypoxxy I can extend the instance methods by adding his answer to a initializer

2 Answers 2

2

You can do

Globalize::ActiveRecord::InstanceMethods.class_eval do
    # patch methods
end
Sign up to request clarification or add additional context in comments.

2 Comments

where would i put this? In an initilizer?
Yeah. You can make a .rb file at config/initializers/ or you should be able to put it in lib folder also
1

You probably just need to be sure you require the module before monkeypatching it; if it is relying on the autoloader to load those files, then defining them will prevent the autoloader from attempting to require them. Globalize is indeed relying on the autoloader, as seen here.

To fix it, explicitly require those modules before patching them:

 require 'globalize'
 require 'globalize/active_record'
 require 'globalize/active_record/instance_methods'

 # Patch your stuff here.

3 Comments

Hmm, didnt get it to work. perhaps i missplaces them?
Try ensuring that the module exists and has the methods you are interested in before you patch it. What behavior are you seeing?
InstanceMethods, such as translated_attributes gives "undefined method `translated_attributes'". But my foo method is there.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.