by akoumjian · 13y ago · 0 comments
You could do something similar to Ruby's missing_method, by setting the class's __getattr__, but you'd really have to ask yourself why. What kind of creation are you building that you are expecting to not know which methods are available while running your program?
These are the kinds of things that drive me batty with Ruby. Perhaps if I spent about double or triple the hours on Ruby that I have, I might have an "aha" moment. However, from what I've seen I can't help but feel that what it's really trying to accomplish is much more comfortable in functional form (say Lisp?).
You normally wouldn't use method_missing in this way. As an example, for better or worse, look at RSpec. I can write code like this:
require 'rspec'
class Person
def initialize
@happy = true
end
def happy?
@happy
end
end
describe Person do
describe '.new' do
it 'is happy by default' do
expect(Person.new).to be_happy
end
end
end
RSpec doesn't know about the Person#happy? method, obviously, so how the heck is there a be_happy method? It's using method_missing to intercept the call to the otherwise-undefined be_happy method, pull out the "happy" part, translate it to "happy?", and then construct the appropriate expectation by delegating the "happy?" message to the underlying Person object and analyzing the response.It also enables RSpec to generate much more useful testing messages. Instead of saying "Expected person.happy? to be true, but got false" it can say "Expected person to be happy, but happy? returned false."
This intercept-and-delegate or intercept-and-translate mechanism is probably the most common use of method_missing. It makes writing DSLs much easier. See, e.g., Nokogiri::XML::Builder for generating XML documents (http://nokogiri.org/Nokogiri/XML/Builder.html).
In a pinch the (free?) "Barewords" episode of Ruby Tapas will get you close in five minutes.
Well, metaprogramming is all about exactly that kind of thing. Python is a fine language, but it's not cut from the same cloth as Ruby. That's not a value judgement; plenty of sane, creative, and intelligent people use Python. They're simply not the same kind of language.
`method_missing` is more useful for dynamically responding to method calls than actually not knowing how to respond. A good example of this is rails' (version 3.2 and lower) dynamic finders:
User.find_by_username('a_username')
`find_by_username` is never defined anywhere, it is dynamically responded to using method missing. this allows code to be much more precise and DRY (though at the expense of readability if you don't know what's going on)