Ruby refinements: Difference between revisions

From wikinotes
(Created page with "Refinements let you limit the scope of Monkey-Patches.<br> You can override methods, or add new ones, and they will only be applied to classes/modules if they are explicitly i...")
 
No edit summary
Line 1: Line 1:
Refinements let you limit the scope of Monkey-Patches.<br>
Refinements let you limit the scope of Monkey-Patches.<br>
You can override methods, or add new ones, and they will only be applied to classes/modules if they are explicitly included.
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 =
= Documentation =
Line 15: Line 15:
<syntaxhighlight lang="ruby">
<syntaxhighlight lang="ruby">
class User
class User
  def firstname; end
  def lastname; end
end
end
</syntaxhighlight>


<syntaxhighlight lang="ruby">
module Passenger
module Passenger
   refine User
   refine User
Line 27: Line 27:


<syntaxhighlight lang="ruby">
<syntaxhighlight lang="ruby">
# bind monkeypatch within this scope
# uses_refinement.rb
 
# User instances gain 'buckle_seatbelt' -- but only in this file
using Passenger
using Passenger
user = User.new
user.buckle_seatbelt
</syntaxhighlight>


# use monkeypatch
<syntaxhighlight lang="ruby">
# doesnt_use_refinement.rb
user = User.new
user = User.new
user.buckle_seatbelt
user.buckle_seatbelt # raises exception -- 'buckle_seatbelt not defined'
</syntaxhighlight>
</syntaxhighlight>
</blockquote><!-- Example -->
</blockquote><!-- Example -->

Revision as of 15:26, 14 May 2022

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'