Skip to content

Instantly share code, notes, and snippets.

@afcapel
Last active August 29, 2015 14:05
Show Gist options
  • Save afcapel/fe168398d23327645e1d to your computer and use it in GitHub Desktop.
Save afcapel/fe168398d23327645e1d to your computer and use it in GitHub Desktop.
require 'delegate'
class NumberDecorator < SimpleDelegator
def in_dollars
"$#{to_s}"
end
def in_euros
"€#{to_s}"
end
def in_pounds
"£#{to_s}"
end
# Any other method will be delegated to the wrapped object
end
amount = NumberDecorator.new(13.5)
puts amount.in_dollars
# => $13.5
puts amount.in_pounds
# => £13.5
puts amount.floor # method delegated to the 13.5 Float object
# => 13
puts amount.ceil # another delegated method
# => 14
# Change the wrapped object, if you want
amount.__setobj__(24.8)
puts amount.in_dollars
# => $24.8
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment