Skip to content

Instantly share code, notes, and snippets.

@JoshCheek
Created August 12, 2019 20:05
Show Gist options
  • Save JoshCheek/7cc84715dc7ab6deef40adf9982bf755 to your computer and use it in GitHub Desktop.
Save JoshCheek/7cc84715dc7ab6deef40adf9982bf755 to your computer and use it in GitHub Desktop.
Using a refinement to scope a monkey patch
# 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