Created
October 4, 2012 16:11
-
-
Save sgharms/3834658 to your computer and use it in GitHub Desktop.
Delegators and composition in Ruby
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 Kitchen | |
def prepare_hamburger | |
return ( %w/ artisinal_bun niman_ranch_beef cowgirl_creamery_bleu_cheese lettuce central_valley_avocado/. | |
join ', ' ) + " hamburger." | |
end | |
def generate_mixin | |
Module.new do | |
def prepare_hamburger | |
puts "Enjoy a: " + @kitchen.prepare_hamburger | |
end | |
end | |
end | |
end | |
class Restaurant | |
def initialize(name) | |
@name = name | |
@kitchen = Kitchen.new | |
self.extend @kitchen.generate_mixin | |
end | |
end | |
my_resto = Restaurant.new "The Stinky Cow" | |
my_resto.prepare_hamburger |
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
#!/usr/bin/env ruby | |
# | |
# The Goal: Use composition effectively. A Restaurant purports to "prepare a hamburger," but we | |
# know that it is actually the responsibility of the kitchen to do the work. | |
# | |
# Key feature: the token used for the action is the SAME between the two entitites `prepare_hamburger`. | |
# | |
# Desired: A way to have Restaurant delegate :prepare_hamburger to Kitchen **AND** | |
# **do not** define the wrapper :prepare_hamburger on Restaurant. | |
class Kitchen | |
def prepare_hamburger | |
return ( %w/ artisinal_bun niman_ranch_beef cowgirl_creamery_bleu_cheese lettuce central_valley_avocado/. | |
join ', ' ) + " hamburger." | |
end | |
end | |
class Restaurant | |
def initialize(name) | |
@name = name | |
@kitchen = Kitchen.new | |
end | |
def prepare_hamburger | |
puts "Enjoy a: " + @kitchen.prepare_hamburger | |
end | |
end | |
my_resto = Restaurant.new "The Stinky Cow" | |
my_resto.prepare_hamburger |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If your goal is to use composition effectively, and then you call
#extend
, you've failed, because mixins are inheritance, not composition. ;)That said, I sorta agree with James; I'm also not sure what the point is... :/