views:

35

answers:

2

Dear all,

I'm working on a rails3 app and I'm a little bit confused with Active Model. Here is my model :

class MyClass
 include ActiveModel::Validations
 include ActiveModel::Conversion
 extend ActiveModel::Naming

 attr_accessor :foo, :foo1, foo2

  def initialize(attributes = {})
    attributes.each { |key, value| send "#{key}=", value }
  end

  def self.all
    get_elig
  end

private

  def self.get_elig
   # My function
  end
end

The get_elig function return a Hash like this one : {"foo1"=>"bar1", "foo2"=>"bar2", "foo"=>"bar"}

Under the rails console :

irb(main):031:0> t = MyClass.all
=> {"foo1"=>"bar1", "foo2"=>"bar2", "foo"=>"bar"}
irb(main):032:0> t.foo
NoMethodError: undefined method `foo' for #<Hash:0x105e96be0>

My question is simple : what was going wrong with my model ?

Thanks for help.

A: 

As you said: MyClass.all returns a hash object and you can not use dot notation on a hash.

What you probably want is to initialize your class with the hash: x = MyClass.new({"foo1" => "bar1"}). Now you have access with dot notation as the implementation suggests.

Stevens
Not exactly.MyClass.all call a SOAP api and return a hash of object. What I wanted to do was to convert hash['key'] to hash.key. After doing this whith my own method I've used the Hashie gem that saved my life.
jjmartres
A: 

Not exactly.

MyClass.all call a SOAP API and return a hash of object.

What I wanted to do was to convert hash['key'] to hash.key. After doing this whith my own method I've used this Gem that saved my life.

Hope that helps someone :)

jjmartres