Class: Gearbox::AttributeCollection

Inherits:
Object
  • Object
show all
Defined in:
lib/gearbox/attribute_collection.rb

Overview

Collects attributes in a hash-like format. Serializes the attributes in an OpenStruct.

Instance Method Summary collapse

Constructor Details

#initialize(default = {}) ⇒ AttributeCollection

Build a new AttributeCollection with an optional Hash.

Note: this class normalizes the keys and creates OpenStructs for values.

Parameters:

  • default (Hash) (defaults to: {})

    A hash with normalized keys and OpenStruct values

Raises:

  • (ArgumentError)


11
12
13
14
15
# File 'lib/gearbox/attribute_collection.rb', line 11

def initialize(default={})
  raise ArgumentError, "Must provide a hash for the defaults" unless default.is_a?(Hash)
  @default = default
  @source = {}
end

Instance Method Details

#[](key) ⇒ OpenStruct?

Get one attribute from the collection.

Parameters:

  • key (String, Symbol)

Returns:

  • (OpenStruct, nil)

    Returns the attribute OpenStruct, if found.



29
30
31
# File 'lib/gearbox/attribute_collection.rb', line 29

def [](key)
  @source[normalize_key(key)]
end

#[]=(key, hash) ⇒ OpenStruct

Set one attribute in the collection.

Parameters:

  • key (String, Symbol)
  • hash (Hash)

Returns:

  • (OpenStruct)

    The hash, converted into an OpenStruct

Raises:

  • (ArgumentError)


21
22
23
24
# File 'lib/gearbox/attribute_collection.rb', line 21

def []=(key, hash)
  raise ArgumentError, "Must provide a hash for the value" unless hash.is_a?(Hash)
  @source[normalize_key(key)] = OpenStruct.new(@default.merge(hash))
end