Created
May 19, 2012 16:16
-
-
Save practicingruby/2731370 to your computer and use it in GitHub Desktop.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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