Search code examples
rubymonkeypatching

Monkey patching inside module to limit its scope


Why does this throw an error, when the class and statement is encapsulated in the module??

module Xchange

  class Float

    def in currency
      self.to_s << " " << suffix(currency)
    end

    private

    def suffix currency
      case currency
      when :euro
        "euros"
      when :dollar
        "dollars"
      when :rupee
        "rupees"
      end
    end

  end

  puts 2.3.in(:euro)
end

Solution

  • Opps, my mistake! It took me a while to figure out! Just tried to look inside the Float class using Pry and to my surprise found that there are no other Float methods in it. So, I am assuming the Float I was trying to re-define was not the globally available Float. It a new class by the name Xchange::Float with a single instance method in!

    So, in short I believe such a patch will be global and to all files that requires it. Hence the point of refine in the new version.