Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Make ActiveResource models generate hashes for nested objects

In my application, I‘m using ActiveResource to manage the data that I receive from a remote API. Say, one of my models is called Account and it has a field called settings, which is documented in the API as a “freeform hash”, meaning it can store whatever.

A sample simplified JSON I would receive from the API:

{
    "account": {
        "title": "My Account",
        "settings": {
            "a_random_setting": true,
            "another_random_setting": 42,
            "a_subconfig_of_sorts": {
                "is_deep": true
            }
        }
    }
}

ActiveResource very kindly goes all the way down the deepest nested objects in that JSON and turns them all into Ruby objects:

my_account.settings # => Account::Settings
my_account.settings.a_subconfig_of_sorts # => Account::Settings::ASubconfigOfSorts

This makes it a bit difficult to look up dynamic keys within that the content of settings. Essentially, I would much rather have settings as regular hash, and not a custom nested object generated for me on the fly.

my_account.settings.class # => Hash
my_account.settings[:a_subconfig_of_sorts] # => {:is_deep => true}

How do I make ActiveResource do that? My first guess was by using the schema declaration, but that only provides scalar types, it seems.

like image 977
Arnold Avatar asked May 20 '26 04:05

Arnold


1 Answers

Made solution that works with that issue. Hope that helps.

class Account < ActiveResource::Base
  create_reflection :settings_macro, :settings, class_name: 'Account::Hash'  
  class Hash < ::Hash
    def initialize(hash, persisted)
      merge!(hash)
    end
  end
end
like image 60
Ruslan Kyrychuk Avatar answered May 21 '26 17:05

Ruslan Kyrychuk



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!