Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
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
You can’t perform that action at this time.