Ruby refinements: Difference between revisions
From wikinotes
No edit summary |
|||
(5 intermediate revisions by the same user not shown) | |||
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 in files where the refinement is used. | You can override methods, or add new ones, and they will only be applied to classes/modules in files where the refinement is used. | ||
I could see this being useful for monkey-patching 3rd party libraries. | |||
= Documentation = | = Documentation = | ||
Line 20: | Line 22: | ||
module Passenger | module Passenger | ||
refine User | refine User do | ||
def buckle_seatbelt; end | def buckle_seatbelt; end # method added to 'User' instances if 'using Passenger' | ||
end | end | ||
end | end | ||
Line 27: | Line 29: | ||
<syntaxhighlight lang="ruby"> | <syntaxhighlight lang="ruby"> | ||
# | # has_refinement.rb | ||
# User instances gain 'buckle_seatbelt' -- but only in this file | using Passenger # User instances gain 'buckle_seatbelt' -- but only in this file | ||
user = User.new | user = User.new | ||
user.buckle_seatbelt | user.buckle_seatbelt | ||
Line 36: | Line 37: | ||
<syntaxhighlight lang="ruby"> | <syntaxhighlight lang="ruby"> | ||
# | # no_refinement.rb | ||
user = User.new | user = User.new | ||
user.buckle_seatbelt # raises exception -- 'buckle_seatbelt not defined' | user.buckle_seatbelt # raises exception -- 'buckle_seatbelt not defined' | ||
</syntaxhighlight> | </syntaxhighlight> | ||
</blockquote><!-- Example --> | </blockquote><!-- Example --> |
Latest revision as of 14:51, 20 June 2023
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.
I could see this being useful for monkey-patching 3rd party libraries.
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 do def buckle_seatbelt; end # method added to 'User' instances if 'using Passenger' end end# has_refinement.rb using Passenger # User instances gain 'buckle_seatbelt' -- but only in this file user = User.new user.buckle_seatbelt# no_refinement.rb user = User.new user.buckle_seatbelt # raises exception -- 'buckle_seatbelt not defined'