Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does Ruby have a method_missing equivalent for undefined instance variables?

When I invoke a method that doesn't exist, method_missing will tell me the name of the method. When I attempt to access a variable that hasn't been set, the value is simply nil.

I'm attempting to dynamically intercept access to nil instance variables and return a value based on the name of the variable being accessed. The closest equivalent would be PHP's __get. Is there any equivalent functionality in Ruby?

like image 541
meagar Avatar asked Oct 04 '11 16:10

meagar


People also ask

What is Method_missing in Ruby?

What is method_missing? method_missing is a method that ruby gives you access inside of your objects a way to handle situations when you call a method that doesn't exist. It's sort of like a Begin/Rescue, but for method calls. It gives you one last chance to deal with that method call before an exception is raised.

What is a Ruby instance variable?

What's an instance variable? In the Ruby programming language, an instance variable is a type of variable which starts with an @ symbol. Example: @fruit. An instance variable is used as part of Object-Oriented Programming (OOP) to give objects their own private space to store data.

Are instance variables inherited in Ruby?

Instance variables are not inherited. If a method is written in the subclass with the same name and parameters as one in the parent class, the super class' method is overwritten.

CAN modules have instance variables Ruby?

Explanation: Yes, Module instance variables are present in the class when you would include them inside the class.


2 Answers

I do not believe this is possible in Ruby. The recommended way would be to use a ''user'' method rather than a ''@user'' instance var in your templates.

This is consistent with the way you deal with Ruby objects externally (''obj.user'' is a method which refers to ''@user'', but is actually not ''@user'' itself). If you need any kind of special logic with an attribute, your best bet is to use a method (or method_missing), regardless if you're accessing it from inside or outside the object.

like image 177
bioneuralnet Avatar answered Oct 11 '22 20:10

bioneuralnet


See my answer to another similar question. But just because you can do it doesn't mean that it's a good idea. Sensible design can generally overcome the need for this kind of thing and allow you to produce more readable and hence maintainable code.

instance_variable_get seems to be the closest equivalent of PHP's __get from what I can see (although I'm not a PHP user).

Looking at the relevant Ruby source code, the only 'missing' method for variables is const_missing for constants, nothing for instance variables.

like image 29
Carl Suster Avatar answered Oct 11 '22 22:10

Carl Suster