Skip to content

Instantly share code, notes, and snippets.

@ingeniarius
Forked from ernie/dance.rb
Created September 24, 2012 13:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ingeniarius/3776000 to your computer and use it in GitHub Desktop.
Save ingeniarius/3776000 to your computer and use it in GitHub Desktop.
Dependency Injection
#!/usr/bin/env ruby
require './dancer'
require './gangnam_style'
dancer = Dancer.new('PSY', GangnamStyle.new)
dancer.dance!
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
# 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