Created
August 12, 2019 20:05
-
-
Save JoshCheek/7cc84715dc7ab6deef40adf9982bf755 to your computer and use it in GitHub Desktop.
Using a refinement to scope a monkey patch
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# code we don't own | |
class User | |
def initialize(first_name, last_name) | |
@first_name, @last_name = first_name, last_name | |
end | |
def full_name | |
@first_name + " " + @last_name | |
end | |
end | |
# code we do own | |
module FixUserFullName | |
refine User do | |
def full_name | |
name = @first_name | |
name += " #@last_name" if @last_name | |
name | |
end | |
end | |
end | |
class MyMailer | |
using FixUserFullName | |
def send_invitation(user) | |
"Welcome, #{user.full_name}" | |
end | |
end | |
josh = User.new 'Josh', nil | |
josh.full_name rescue $! # => #<TypeError: no implicit conversion of nil into String> | |
MyMailer.new.send_invitation(josh) # => "Welcome, Josh" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment