class Gearbox::AttributeCollection
Collects attributes in a hash-like format. Serializes the attributes in an OpenStruct.
Public Class Methods
new(default={})
click to toggle source
Build a new AttributeCollection
with an optional Hash.
Note: this class normalizes the keys and creates OpenStructs for values. @param [Hash] default A hash with normalized keys and OpenStruct values
# 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
Public Instance Methods
[](key)
click to toggle source
Get one attribute from the collection. @param [String, Symbol] key @return [OpenStruct, nil] Returns the attribute OpenStruct, if found.
# File lib/gearbox/attribute_collection.rb, line 29 def [](key) @source[normalize_key(key)] end
[]=(key, hash)
click to toggle source
Set one attribute in the collection. @param [String, Symbol] key @param [Hash] hash @return [OpenStruct] The hash, converted into an OpenStruct
# 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
Private Instance Methods
normalize_key(obj)
click to toggle source
Normalizes the key. Converts to a lower case symbol with non-alpha-numerics replaced by underscores, removing trailing and preceding underscores. @private
# File lib/gearbox/attribute_collection.rb, line 37 def normalize_key(obj) obj.to_s.downcase.gsub(/[^A-Za-z0-9_]+/, '_').gsub(/(_$)|(^_)/, '').to_sym end