Skip to content

Instantly share code, notes, and snippets.

@joonyou
Created August 13, 2013 18:11
Show Gist options
  • Save joonyou/6223962 to your computer and use it in GitHub Desktop.
Save joonyou/6223962 to your computer and use it in GitHub Desktop.
code from visitor pattern screencast
class Goodie
attr_accessor :price
def initialize(price)
@price = price
end
def accept(visitor)
visitor.visit(self)
end
end
class TaxManVisitor
def initialize(rate)
@rate = rate / 100.0
end
def visit(obj)
if obj.respond_to? :price
obj.instance_eval { class << self; attr_accessor :tax; end }
obj.tax = obj.price * @rate
end
end
end
x = Goodie.new(25)
puts "price is #{x.price}"
x.accept TaxManVisitor.new(9)
puts "tax is #{x.tax}"
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment