I don't think you will achieve the desired result with this approach. What are you trying to do?
As far as I know you should be namespacing your gem classes properly anyway. Meaning you wrap all of your class definitions in a module named after your gem:
module MyGem
class MyRecord < ActiveRecrod::Base
#some stuff like def self.gem_method
end
end
This way the definition of your classes don't interfere unintentionally with the application using the gem or in a way that is non transparent (i.e. confusing) for the user.
If the user really wants to use the MyRecord
class as delivered by the gem he can just refer to it like MyGem::MyRecord
, e.g. he could do
class MyRecord < MyGem::MyRecord
This would be the solution if you want to really seperate the two classes.
If you actually aim to monkey patch a class defined in the application: just don't.
Instead, provide the methods you want to be given by the gem in a module
module MyFunctionality
def gem_method
# ...
end
end
and let the user include this by the class that should be able to access these methods:
class MyRecord < ActiveRecord::Base
include MyFunctionality
# ...
end
This needs to be actively done by the user of your gem but this way it does not happen unintentionally. So the "problem" you described is actually a feature for better transperancy. If I come up with an explanaition why it technically works as you describe, I'll let you know. But for the moment I suggest you accept it and solve it in a way that is more compliant with ruby best practices.
If you want to read more about Monkey Patching and module inclusions; The top answer to this question describes very well what you should do and why: When monkey patching a method, can you call the overridden method from the new implementation?
Please let me know if you have questions about my answer.