Today I Learned

hashrocket A Hashrocket project

Refinements

In Ruby 2.1 and later, you can require monkey patching to be explicitly active inside of a class/module by defining your method inside of a refine block. You can activate the changes with the using keyword.


​module Confusion
  refine String do
    def length
      "Yes"
    end
  end
end

module BadString
  using Confusion
  def self.count(string)
    string.length
  end
end

module GoodString
  def self.count(string)
    string.length
  end
end

BadString.count("four") # => "Yes"
GoodString.count("four") # => 4
See More #ruby TILs
Looking for help? Each developer at Hashrocket has years of experience working with Ruby applications of all types and sizes. We're an active presence at Ruby conferences, have written some of the most popular gems, and have worked on many of the web's Ruby on Rails success stories. Contact us today to talk about your Ruby project.