Mixing in a module within Object causes all Objects to inherit that module's instance methods as singleton methods

百般思念 提交于 2019-12-14 03:17:57

问题


When attempting to add my own behavior to the Object class, I get undesired effects that don't occur when mixing the module into a user-defined class.

module Entity
  def some_instance_method
    puts 'foo'
  end

  def self.secret_class_method
    puts 'secret'
  end

  module ClassMethods
    def some_class_method
      puts 'bar'
    end
  end

  def self.included( other_mod )
    other_mod.extend( ClassMethods )
  end
end

Now, I create class Bob such that it includes Entity.

class Bob; include Entity; end;

This yields the desired and expected output:

Bob.secret_class_method       #=> NoMethodError
Bob.some_instance_method      #=> NoMethodError
Bob.some_class_method         #=> bar
Bob.new.secret_class_method   #=> NoMethodError
Bob.new.some_instance_method  #=> foo
Bob.new.some_class_method     #=> NoMethodError

But if instead of defining class Bob I were to open up class Object and include Entity like so:

class Object; include Entity; end

Then the output I see is this:

Object.secret_class_method        #=> NoMethodError
Object.some_instance_method       #=> foo
Object.some_class_method          #=> bar
Object.new.secret_class_method    #=> NoMethodError
Object.new.some_instance_method   #=> foo
Object.new.some_class_method      #=> NoMethodError

If I then define class Bob, it behaves in the same way: some_instance_method can be called on class Bob. It seems as though something about the Object class itself is messing with the behavior of this pattern, or else I'm just doing something wrong here. Can someone please explain this odd behavior? I don't want all my Objects to inherit instance methods as singleton methods as well!


回答1:


Bob ia an object (more precisely: Bob is an instance of Class, which is a subclass of Module which is a subclass of Object, which is a subclass of Entity), therefore it has Entity's methods. That's just how inheritance works.



来源:https://stackoverflow.com/questions/17687200/mixing-in-a-module-within-object-causes-all-objects-to-inherit-that-modules-ins

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!