Messing with Ruby metaprogramming
I recently got back to an old set of Ruby lines I was designing to automate and add an email-driven workflow for some downloading tool I was writing, and found something I didn’t remember…
In dynamic languages, the binding of any methods being done at runtime trying to reach an unknown method would call the method_missing method to intercept - and/or re-route - the call to the missing method. A simple example can be:
class MyClass
def method_missing(method_id, *args)
puts "re-routing to method say with param: #{args.shift}"
send('say', method_id,*args)
end
def say(*args)
puts args.shift
end
end
And now with irb you can try
irb(main):099:0> a.hello "world"
re-routing to method say with param: world
hello
=> nil
What’s even more exciting is that you can also mess with the unknown classes !
def Object.const_missing(sym)
Object.const_set( sym, Class.new() )
end
Now you can try whatever you like:
irb(main):103:0> Blah.new
=> #
irb(main):104:0> FooBar.new
=> #
irb(main):105:0> Awesome.new
=> #
You can of course imagine a combination of both the method missing interception and the object missing - actually const_missing - to maximize… the fun.
That was my first post on the funny things you can do with Ruby but with no actual practical and useful usage ![]()