How to map hash keys to methods for an encapsulated Ruby class (tableless model)?
- by user502052
I am using Ruby on Rails 3 and I am tryng to map a hash (key, value pairs) to an encapsulated Ruby class (tableless model) making the hash key as a class method that returns the value.
In the model file I have
class Users::Account #< ActiveRecord::Base
def initialize(attributes = {})
@id = attributes[:id]
@firstname = attributes[:firstname]
@lastname = attributes[:lastname]
end
end
def self.to_model(account)
JSON.parse(account)
end
My hash is
hash = {\"id\":2,\"firstname\":\"Name_test\",\"lastname\":\"Surname_test\"}
I can make
account = Users::Account.to_model(hash)
that returns (debugging)
---
id: 2
firstname: Name_test
lastname: Surname_test
That works, but if I do
account.id
I get this error
NoMethodError in Users/accountsController#new
undefined method `id' for #<Hash:0x00000104cda410>
I think because <Hash:0x00000104cda410> is an hash (!) and not the class itself. Also I think that doing account = Users::Account.to_model(hash) is not the right approach.
What is wrong? How can I "map" those hash keys to class methods?