Reputation: 1853
I am working on ruby rails project. I am using Rails 2.3.4 and ruby 1.8.7 . I have a model called User.
I have following code in initializer
$h = {User => 'I am user' }
In the controller I have following code
$h[User]
First time when I do h[User] I get the right result. However if I refresh the page then I get nil value.
I think this is what is happening.
First time when User class is loaded then I get the right value. However when I refresh the page then this time controller returns nil value for $h[User].
Because rails unloads all the constants when page is refreshed so it seems a new User class is loaded. This User class is different from the User that was used as key in initializer.
I know using User class is a bad practice. My question is can someone explain to me when User class is used as key then internally how ruby stores the key. Does ruby use object_id of User as the key? I
Upvotes: 1
Views: 135
Reputation: 5774
Hash
calls the hash
method on any objects used as a key. And yes, your theory as to why your code isn't working is correct.
Try this in the Rails console:
User.hash # => 215678765 (or whatever)
reload!
User.hash # => 215876673
Reloading the class changed the value returned by the hash
method, meaning it is no longer the same key when used in a Hash
.
Use :user
or something else that will resolve to the same key every time.
Upvotes: 4