3

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.

Arnold
  • 2,390
  • 1
  • 26
  • 45

1 Answers1

3

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
Ruslan Kyrychuk
  • 366
  • 1
  • 7