Skip to content

Instantly share code, notes, and snippets.

@Amokrane
Created May 22, 2011 12:51
Show Gist options
  • Save Amokrane/985434 to your computer and use it in GitHub Desktop.
Save Amokrane/985434 to your computer and use it in GitHub Desktop.
Using method_missing properly by calling `super`
# This snippet is taken from:
# "The Polite Programmer's Guide to Ruby Etiquette"
# http://bit.ly/hrwdPY
class BlackMagicStereo < Stereo
def method_missing(name, *args)
if sym.to_s =~ /^play_(\w+)$/
system("open songs/#{$1}.m4a")
else
# Here, very important!
# Don't forget to delegate up to previous implementation
super
end
end
end
stereo = BlackMagicStereo.new
stereo.play_back_magic_woman # This works
# This fails if you don't call `super`
# Because it's defined somewhere in the inherited classes
stereo.play("Magic Bus")
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment