In your two examples, you are not actually defining methods in a Class or Module ; you define singleton methods for an object that is Class or Module , but can be almost any object. Here is an example with String :
Diff = "Use me to access really cool methods" def Diff.patch
You can do any of these, and this will work, but the best way to group related methods in Module like normal instance methods (i.e. without self. ):
module Diff extend self
Now you can:
- use this functionality from any class (with
include Diff ) or from any object (using extend Diff ) - an example of this use is the
extend self line, which allows Diff.patch to be called. - even use these methods in the global namespace
For example, in irb :
class Foo include Diff end Foo.new.patch
Note: extend self will "modify" the Diff module object itself, but it will not affect module inclusion. The same thing happens for def self.foo , foo will not be accessible to any class, including it. In short, only instances of the Diff method are imported using include (or extend ), not single methods. Only subclassing the class will ensure the inheritance of both the instance method and the singleton method.
If you really want to include a module to provide both instance methods and singleton methods, this is not entirely easy. You should use self.included hook:
module Foo def some_instance_method; end module ClassMethods def some_singleton_method; end end def self.included(base) base.send :extend, ClassMethods end def self.will_not_be_included_in_any_way; end end class Bar include Foo end
source share