Skip to content

Instantly share code, notes, and snippets.

@mpelzsherman
Created May 23, 2014 19:47
Show Gist options
  • Save mpelzsherman/c0896ae43a95b8572d7c to your computer and use it in GitHub Desktop.
Save mpelzsherman/c0896ae43a95b8572d7c to your computer and use it in GitHub Desktop.
Random House using strategy pattern
class House
attr_accessor :os
def initialize(os=DefaultOrderingStrategy.new)
@os = os
end
def recite
(1..actors.length).map { |i| line(i) }.join("\n")
end
def line(number)
"This is %s.\n" % [actors.last(number).zip(actions.last(number)).join(' ')]
end
private
def actors
@actors ||= os.order([
'the horse and the hound and the horn',
'the farmer sowing his corn',
'the rooster that crowed in the morn',
'the priest all shaven and shorn',
'the man all tattered and torn',
'the maiden all forlorn',
'the cow with the crumpled horn',
'the dog',
'the cat',
'the rat',
'the malt',
'the house'
])
end
def actions
@actions ||= os.order([
'that belonged to',
'that kept',
'that woke',
'that married',
'that kissed',
'that milked',
'that tossed',
'that worried',
'that killed',
'that ate',
'that lay in',
'that Jack built'
])
end
end
class DefaultOrderingStrategy
def order(array)
array
end
end
class RandomOrderingStrategy
def order(array)
array.shuffle
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment