I was trying to write my first method_missing override when I kept running into (edited) stack level too deep errors. The main culprit seemed to be trying to utilize an instance attribute. For instance if ‘self’ was a instance of the User class then checking for something like:
def method_missing(name)
if self.name
# do stuff
end
end
Would seg fault. I spent a long time on this but ended up giving up. There must be something I’m not understanding about accessing it.
Edit
My apologies, Andrew is correct, I am getting Stack Level too deep errors. With this in mind, what is the appropriate (if any) way to access the instances attribute values?
You can potentially rectify this problem by ensuring that
self.nameactually exists:Note this may not work if your class inherits from anything Railsy (e.g.
ActiveRecord::Base), since it overridesrespond_to?.If you are in a Railsy class, your method missing should call
super, lest you lose a lot of the “magic” ActiveRecord methods (including, probably,self.nameitself):Obviously you should replace
name_is_something_i_should_handle_herewith the appropriate logic.You may also wish to consider using dynamic method creation instead of
method_missing.