Skip to content
Philip (flip) Kromer edited this page May 21, 2012 · 5 revisions

gorillib/collection -- associative arrays of keyed objects

Collection flexibly exchanges {name => obj} and [ obj_with_name, obj_with_name, ... ] -- this makes Mongo and JSON happy.

Collection type

Defining

  class Continent
    include Gorillib::Record
    # ...
    field :countries, Collection, :of => Geo::Country, :key_method => :country_id
  end

Lets it serialize as

- name:             Africa
  countries:
    - name:           Rwanda
      country_id:     rw
      capitol_city:   Kigali
    - name:           Djibouti
      country_id:     dj
      capitol_city:   Djibouti

or naturally pivot to be

{ name:               "Africa",
  countries: {
    rw: {
      name:           "Rwanda",
      country_id:     "rw",
      capitol_city:   "Kigali" },
    dj: {
      name:           "Djibouti",
      country_id:     "dj",
      capitol_city:   "Djibouti" },
  }
}

Calling Collection.receive works on either representation, and calling to_a or to_hash does what you'd think:

   africa.countries.to_a    # [ <Geo::Country name="Rwanda"...>, <Geo::Country name="Djibouti"...> ]
   africa.countries.to_hash # { :rw => <Geo::Country name="Rwanda"...>, :dj => <Geo::Country name="Djibouti"...> }

Collection proxies a small set of methods to an internal Hash. We purposefully keep you from calling methods that work differently on Hash and Array -- most notably, there is no each method, and it is currently not an Enumerable.

  • each_pair iterates over the key/value pairs

  • each_value iterates over the values

  • to_a gives the list of values

  • to_hash gives a duplicate of the proxied hash

  • inspect, to_s, as_json and to_json show a list of values -- it serializes like an array

  • merge!, concat or receive! add values in-place, and merge to a duplicate, as follows:

    • if the given collection responds_to to_hash, it is merged into the internal collection; each hash key must match the id of its value or results are undefined.
    • otherwise, it merges a hash generates from the id/value pairs of each object in the given collection.
  • []= adds a single value with a specified key; that key must match the value's id or it is undefined behavior.

  • << adds a single value at the right key.

  • build(attributes={})

advanced use

  • key_method (read-only class attribute, a Symbol) defines how to find the id; by default, :id
  • factory (read-only class attribute) defines how to create a new item given its raw material. This is handed to Gorillib::Factory for conversion the first time it's read.

Decisions

Mysteries

  • ?? no each method
  • ?? Enumerable