Ruby refinements

From wikinotes
Revision as of 15:26, 14 May 2022 by Will (talk | contribs)

Refinements let you limit the scope of Monkey-Patches.
You can override methods, or add new ones, and they will only be applied to classes/modules in files where the refinement is used.

Documentation

official docs https://docs.ruby-lang.org/en/3.0.0/doc/syntax/refinements_rdoc.html

Example

class User
  def firstname; end
  def lastname; end
end

module Passenger
  refine User
    def buckle_seatbelt; end
  end
end
# uses_refinement.rb

# User instances gain 'buckle_seatbelt' -- but only in this file
using Passenger
user = User.new
user.buckle_seatbelt
# doesnt_use_refinement.rb
user = User.new
user.buckle_seatbelt # raises exception -- 'buckle_seatbelt not defined'