Class: Linecook::Attributes

Inherits:
Object
  • Object
show all
Defined in:
lib/linecook/attributes.rb

Overview

Attributes provides a context for specifying default attributes. For example:

attributes = Attributes.new
attributes.instance_eval %{
  attrs['a'] = 'A'
  attrs['b']['c'] = 'C'
}

attributes.to_hash
# => {'a' => 'A', 'b' => {'c' => 'C'}}

Note that attrs is an auto-filling nested hash, making it easy to set nested attributes, but it is not indifferent, meaning you do need to differentiate between symbols and strings. Normally strings are preferred.

Constant Summary collapse

NEST_HASH_PROC =

A proc used to create nest_hash hashes

Proc.new do |hash, key|
  hash[key] = Hash.new(&NEST_HASH_PROC)
end

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeAttributes

Returns a new instance of Attributes.



50
51
52
# File 'lib/linecook/attributes.rb', line 50

def initialize
  @attrs = Attributes.nest_hash
end

Instance Attribute Details

#attrsObject (readonly)

An auto-filling nested hash



48
49
50
# File 'lib/linecook/attributes.rb', line 48

def attrs
  @attrs
end

Class Method Details

.disable_nest_hash(hash) ⇒ Object

Recursively disables automatic nesting of nest_hash hashes.



32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/linecook/attributes.rb', line 32

def disable_nest_hash(hash)
  if hash.default_proc == NEST_HASH_PROC
    hash.default = nil
  end
  
  hash.each_pair do |key, value|
    if value.kind_of?(Hash)
      disable_nest_hash(value)
    end
  end
  
  hash
end

.nest_hashObject

Returns an auto-filling nested hash.



27
28
29
# File 'lib/linecook/attributes.rb', line 27

def nest_hash
  Hash.new(&NEST_HASH_PROC)
end

Instance Method Details

#to_hashObject

Disables automatic nesting and returns attrs.



55
56
57
# File 'lib/linecook/attributes.rb', line 55

def to_hash
  Attributes.disable_nest_hash(attrs)
end