How can I call a static method in a Ruby module from a class that includes the module?
Is it possible to declare static methods in a module in ruby?
module Software
def self.ex开发者_如何学编程it
puts "exited"
end
end
class Windows
include Software
def self.start
puts "started"
self.exit
end
end
Windows.start
The example above will not print out "exited".
Is it only possible to have instance methods in a module?
Define your module like this (i.e. make exit
an instance method in the module):
module Software
def exit
puts "exited"
end
end
and then use extend
rather than include
class Windows
extend Software
# your self.start method as in the question
end
In use:
irb(main):016:0> Windows.start
started
exited
=> nil
Explanation
obj.extend(module, ...) adds to obj the instance methods from each module given as a parameter
...so when used within the context of a class definition (with the class itself as the receiver) the methods become class methods.
Put your class methods in a nested module, and then override the "included" hook. This hook is called anytime your module is included. Inside the hook, add the class methods to whomever did the include:
module Foo
def self.included(o)
o.extend(ClassMethods)
end
module ClassMethods
def foo
'foo'
end
end
end
Now any class including Foo gets a class method named foo:
class MyClass
include Foo
end
p MyClass.foo # "foo"
Any non-class methods may be defined in Foo as usual.
Two things need to change to be able to call Windows.exit
:
Software#exit
needs to be an instance methodWindows
needs toextend
Software
, notinclude
it.
This is because extend
ing another module puts that module's instance methods as the current module's class methods, whereas include
ing a module puts the methods as new instance methods.
module Software
def exit
puts "exited"
end
end
class Windows
extend Software
def self.start
puts "started"
self.exit
end
end
Windows.start
Output is:
started exited
It is possible to include static methods in a module:
module Software
def self.exit
puts "exited"
end
end
Software.exit
Running this prints 'exited' as expected.
精彩评论