How to improve a module in Ruby?

You can improve your class with

module RefinedString refine String do def to_boolean(text) !!(text =~ /^(true|t|yes|y|1)$/i) end end end 

but how to clarify the module method? It:

 module RefinedMath refine Math do def PI 22/7 end end end 

raises: TypeError: wrong argument type Module (expected Class)

+7
source share
2 answers

Well, since defining a #method module is equivalent to defining an instance method on #singleton_class , the following will work:

 module Math def self.pi puts 'original method' end end module RefinementsInside refine Math.singleton_class do def pi puts 'refined method' end end end module Main using RefinementsInside Math.pi #=> refined method end Math.pi #=> original method 
+8
source share

Refinements change only classes, not modules, so the argument must be a class.

- http://ruby-doc.org/core-2.1.1/doc/syntax/refinements_rdoc.html

Once you realize what you are doing, you have two options for refining module methods around the world. Since ruby ​​has public classes, you can simply override the method:

 Math.exp 2 #⇒ 7.38905609893065module Mathdef self.exp argMath::E ** argendend #⇒ :expMath.exp 2 #⇒ 7.3890560989306495 

If you want to keep the functionality of the method for rewriting:

 module Mathclass << self ▷ alias_method :_____exp, :expdef exp arg_____exp argendendend #⇒ Math ▶ Math.exp 2 #⇒ 7.3890560989306495 

Pay attention to side effects.

+1
source share

All Articles