How to map hash keys to methods for an encapsulated Ruby class (tableless model)?

Posted by user502052 on Stack Overflow See other posts from Stack Overflow or by user502052
Published on 2011-03-05T10:50:56Z Indexed on 2011/03/05 15:25 UTC
Read the original article Hit count: 435

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?

© Stack Overflow or respective owner

Related posts about ruby-on-rails

Related posts about ruby