Created
September 23, 2012 19:59
-
-
Save ernie/3772859 to your computer and use it in GitHub Desktop.
Dependency Injection
This file contains 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 | |
require './dancer' | |
require './gangnam_style' | |
dancer = Dancer.new('PSY', GangnamStyle.new) | |
dancer.dance! |
This file contains 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 Dancer | |
attr_reader :name | |
def initialize(name, dance_style) | |
@name = name | |
@dance_style = dance_style | |
end | |
def dance! | |
@dance_style.dance!(self.name) | |
end | |
end |
This file contains 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
# encoding: UTF-8 | |
class GangnamStyle | |
def initialize(delay = true) | |
@delay = delay | |
end | |
def dance!(name) | |
take_stage(name) | |
cue_music | |
perform_steps | |
stop_music | |
rescue SystemExit, Interrupt => e | |
exit if SystemExit === e | |
ensure | |
stop_music if @music_pid | |
clear_screen | |
end | |
def injected(base) | |
dance_style = self | |
base.singleton_class.class_eval do | |
define_method :dance! do | |
dance_style.dance!(base.name) | |
end | |
end | |
end | |
private | |
def take_stage(name) | |
clear_screen | |
print "\n" * 5 | |
center_print "#{name} has taken the stage..." | |
print "\n" * 5 | |
center_print '/(゜_ ゜)\ ' | |
end | |
def clear_screen | |
print "\e[2J\e[f" | |
end | |
def perform_steps | |
while true do | |
steps.each do |step| | |
center_print step | |
sleep 1 | |
end | |
end | |
end | |
def center_print(message) | |
indent = ' ' * (39 - message.length.to_f / 2) | |
print "#{' ' * 80}\r#{indent}#{message}\r" | |
end | |
def cue_music | |
with_delay do | |
@music_pid = spawn 'mpg123 -q music.mp3' | |
Process.detach @music_pid | |
end | |
end | |
def with_delay(&block) | |
if @delay | |
sleep 5 | |
yield | |
sleep 8 | |
else | |
yield | |
end | |
end | |
def stop_music | |
Process.kill('QUIT', @music_pid) | |
end | |
def steps | |
[ | |
'ヽ(゜∇ ゜)ノ ', | |
'ヘ( ̄ー ̄ヘ) ', | |
' (ノ ̄ー ̄)ノ', | |
' (〜 ̄▽ ̄)〜 ', | |
'〜( ̄△ ̄〜) ', | |
' (☞ ゚∀ ゚)☞ ' | |
] | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment