Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to undefine a variable in ruby?

In ruby, is there a way to "undefine" a variable or constant once it's been defined?

In our rails environemnts, we define one of three contants to be true, depending on the environment: TESTING, DEVELOPMENT, or PRODUCTION. Then, in controller code, we use defined? to see if what environment we're in, ie: defined? PRODUCTION.

Now, I want to unit test some of that environment-specific behavior. My initial attempt was to just set the appropriate constant in my test, and then reset them in teardown. However, I can't figure out how to reset DEVELOPMENT and PRODUCTION such that defined? returns false.

Obviously, a solution would be to just check to see if the appropriate constant is also true in addition to checking if it's defined, but this will result in having to touch a fair amount of existing code.

EDIT: I realize this is definitely NOT the right way to do things. Alas, changing it is a nontrivial task, so I'm looking for an easy way to just unit test what's there now. Plus, I'm also just curious about the lower level language question of whether it's possible to undefine a variable/constant.

like image 383
Scotty Allen Avatar asked Dec 03 '08 23:12

Scotty Allen


1 Answers

I found this answer

Object.send(:remove_const, "TESTING")

If I remember correctly, using send here is kind of a hack, because remove_const is really a private method. You want to ask yourself why you need to define constants PRODUCTION, DEVELOPMENT and TESTING at the same time while they really are mutually exclusive ; that's why I upvoted grepsedawk's answer.

like image 186
vincent Avatar answered Nov 14 '22 21:11

vincent