Letting Modules Extend Themselves

The self. prefix for top-level methods can become a bit cumbersome. You can get rid of it by making a module extend itself:

 module​ ​Moral
 extend​ self
  VERY_BAD = 0
  BAD = 1
 
 def​ ​sin​(badness)
  puts ​"Assessing the sin of ​​#{​badness​}​​"
 end
 end

You’ll see this common idiom in modules—for example, module Math uses it in its code. When applied, a module is used as a namespace and you can write Module.method, like Math.sin. Now if this looks like a class method to you, it is! Remember: A module is of type Class.

 require ​"./moral2"
 
 y = Math.​sin​(Math::PI/4) ​# => 0.70710678118654746
 wrongdoing = Moral.​sin​(Moral::VERY_BAD) ​# => Assessing the sin of 0

If you do an include of the module, you can even invoke its methods without a namespace as long as there’s no ambiguity:

 require ​"./moral2"
 include​ Moral
 
 y = Math.​sin​(Math::PI/4) ​# => 0.70710678118654746
 wrongdoing = sin(Moral::VERY_BAD) ​# => Assessing the sin of 0
..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset