It’s great to pull out common functionality into a module, so you can use it in several classes. But it can be a little awkward to test the module, because you can’t call its methods directly.
Well, unless you can: use extend self to make the module’s instance methods available as class methods. Now you can call the methods of the module directly without having an instance of a class that includes this module.
module ShoutMachine
extend self
def shout(text)
"#{text.upcase}!"
end
end
class BigMachine
include ShoutMachine
end
>> ShoutMachine.shout('booyeah') # => BOOYEAH!
>> BigMachine.new.shout('booyeah') # => BOOYEAH!
This tip was submitted by Nick Stielau.
Rubyでmoduleのメソッド使うときに “extend self” したら、モジュールのクラスメソッド(?)みたいにインスタンス使わずに楽に使えますよ、という話。private以外にmodule_function使う感じ。
You can use HTML tags for formatting. Wrap code in <code> tags and multiple lines of code in <pre><code> tags.