5

Let's say I have some active resource object fetched as the following:

x = Resource.find(some_id)

And x in the remote server has some field h as a complex nested hashes which is represented here as nested active resource objects, but then accessing it is a tedious task, so is it possible to convert h to hash? I can just make another call Resource.get(some_id) and the result will be one big hash, but this is risky as the resource -theoretically- may have changed between subsequent calls, so is there a way to convert active resource object to hash ?

Edit

For more clarification, Suppose that some invoice record r[id=some_id] has attribute extras, which is a hash with the value: {:x=>1, :y=>2, :z=>{:a=>1, :b=>2}}

Then when fetching this record through active resource, we get the following result for extras field, -extracted from the response-:

   "extras"=>
    #<App::Invoice::Extras:0x00000008202cb0
     @attributes=
      {"x"=>1,
       "y"=>2,
       "z"=>
        #<App::Invoice::Extras::Z:0x00000008201978
         @attributes={"a"=>1, "b"=>2},
         @persisted=true,
         @prefix_options={}>},
     @persisted=true,
     @prefix_options={}>,

Then how to convert this extras field to a ruby hash ?

  • can you give a more elaborate example of what you may be wanting to do? – x6iae Jan 27 '16 at 10:57
  • can you try `Resource.find(some_id).as_json` – Arup Rakshit Jan 27 '16 at 11:12
  • @ArupRakshit well as_json only converted the first level of the response to hash, so instead of x.extras, we have now x["extras"], but the value of extras is the same old active resource object. However JSON.parse(x._to_json) did the trick :) –  Jan 27 '16 at 11:25

2 Answers2

3

JSON.parse(x.to_json) did the trick.

0

Try:

x = Resource.find(some_id)
hash = OpenStruct.new(x).to_h

or

hash = OpenStruct.new(x.attributes).to_h
Marat Amerov
  • 406
  • 2
  • 9