1

I have a module that is included in a model. In this module, there is a foo method that I would like to override without modifying the existing model and module code.

My idea was to create a file /lib/my_module_extend.rb. I don't know how to override the method in question because it's not like overriding a method in a class. I usually do:

module MyOriginalClassExtend
  ...
end

MyOriginalClass.class_eval do
  prepend(MyOriginalClassExtend)
end

but class_eval is not possible for a module. Do you have any idea?

Orsay
  • 1,080
  • 2
  • 12
  • 32
  • 2
    check this link https://stackoverflow.com/questions/580314/overriding-a-module-method-from-a-gem-in-rails – zubair khanzada Mar 28 '18 at 08:35
  • 1
    Why not do `class MyOriginalClass; prepend MyOriginalClassExtend; end`? – sawa Mar 28 '18 at 09:06
  • @sawa this would be a possibility but I can't edit the file `MyOriginalClass `. Moreover this isn't the only class the module is included in – Orsay Mar 28 '18 at 09:08
  • 1
    @Orsay: you don't need to edit that file. Write this in another file. It's called "open classes" (and modules, for that matter) – Sergio Tulentsev Mar 28 '18 at 09:13
  • @sawa ok so I had to do it for all the files which include this module ? There are a lot ! – Orsay Mar 28 '18 at 09:33

1 Answers1

0

You can follow the same approach as for open class in ruby. You could just write an extension file in config/initializers and the method will be overridden when the application is loaded.

The below one could be more useful for anyone using Mongoid as the ORM for their application.

I created a extension file for Mongoid::Document module as follows config/initializers/mongoid_document_ext.rb

module Mongoid
  module Document
    def as_json(options={})
      hs = super(options)
      hs["id"] = hs.delete("_id").to_s rescue nil 
      hs
    end
  end
end

This monkey patching worked pretty well for me!