Skip to content

Instantly share code, notes, and snippets.

@practicingruby
Created May 19, 2012 16:16
Show Gist options
  • Select an option

  • Save practicingruby/2731370 to your computer and use it in GitHub Desktop.

Select an option

Save practicingruby/2731370 to your computer and use it in GitHub Desktop.
class Composite
def initialize(obj)
@target = obj
end
def extend(component)
@target = self.class.new(component.new(@target))
end
def method_missing(id, *args, &block)
@target.public_send(id, *args, &block)
end
end
class ListMath < Composite
def sum
reduce(:+)
end
end
class ListFormatter < Composite
def report
"Sum: #{sum}\n"+
"Elements: #{join(", ")}\n"
end
end
c = Composite.new([1,2,3])
c.extend(ListMath)
c.extend(ListFormatter)
puts c.report # OUTPUTS:
# Sum: 6
# Elements: 1, 2, 3
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment