问题
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 Object
s 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