Module: Recliner::Properties::Map::ClassMethods

Defined in:
lib/recliner/properties/map.rb

Instance Method Summary collapse

Instance Method Details

#Map(mapping) ⇒ Object

Creates a new Map class with the given mapping (a hash with exactly one key/value mapping). A Map operates like a Hash, but has strict type enforcement. It also automatically converts its keys and values to the correct type when loading from couch format.

Map classes are cached so that:

Map(String => String).object_id == Map(String => String).object_id

Example

>> Map(String => Date)    # creates a map with String keys and Date values
>> Map(String => Address) # creates a map with String keys and Address values
                          # (Address must be serializable to/from couch format)

Raises:

  • (ArgumentError)


25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/recliner/properties/map.rb', line 25

def Map(mapping)
  raise ArgumentError, 'Exactly one type mapping must be given' unless mapping.keys.size == 1
  
  mapping = mapping.to_a.first
  
  @map_class_cache ||= {}
  @map_class_cache[mapping] ||= begin
    returning Class.new(Recliner::Map) do |klass|
      klass.from, klass.to = mapping
    end
  end
end