Tags

redhat
employment
ripple
interfaces
ncurses
ruby
refs
filesystems
retro gaming
raspberry pi
sinatra
3d printing
nethack
gcc
compiler
fedora
virtfs
project
gaming
vim
grep
sed
aikido
philosophy
splix
android
lvm
storage
bitcoin
projects
sig315
miq
db
polisher
meditation
hopex
conferences
omega
simulator
bundler_ext
rubygems
book review
google code in
isitfedoraruby
svn
gsoc
design patters
jsonrpc
rjr
aeolus
ohiolinuxfest
rome
europe
travel
brno
gtk
python
puppet
conference
fudcon
snap
html5
tips
ssh
linux
hardware
libvirt
virtualization
engineering expo
cloud
rpm
yum
rake
redmine
plugins
screencasting
jruby
fosscon
pidgin
gnome-shell
distros
notacon
presentation
rails
deltacloud
apache
qmf
passenger
syrlug
hackerspace
music
massive attack
crypto
backups
vnc
xsd
rxsd
x3d
mercurial
ovirt
qpid
webdev
haikus
poetry
legaleese
jquery
selenium
testing
xpath
git
sshfs
svg
ldap
autotools
pygtk
xmlrpc
slackware

Aug 28 2009 ruby

Invoking method_missing methods in Ruby

So here’s another quick Ruby tip. Kernel.method_missing is a way to catch all invocations to methods in whatever scope you want that aren’t defined. While discouraged from widespread use, eg since it can be hard to debug and can lead to sloppy programming, it does have legitimate / good use cases, for example ActiveRecord uses it to automatically map methods to database columns without requiring developers to explicitly write a getter/setter for each.

Now lets say you want to invoke a method on an object via reflection / introspection. Normally you would run

object.method("methodname").call params

Object.method returns an instance of the ‘Method’ object, on which you can invoke ‘call’ with parameters to invoke that method. If the named method is not found, an exception is raised.

Unfortunately this will be the case for “methods” handled by methodmissing. To invoke these methods meta-programatically, we use another feature of the ‘Object’ class, send. The Ruby backend uses message passing to invoke methods on objects among other things, and the send method explicitly sends a new method invocation message to your object, which will be caught by methodmissing if not present.

object.send(:methodname, parameters)