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

#load_attrs(path) ⇒ Object

Loads the attributes file into attrs. The loading mechanism depends on the file extname:

.rb: evaluate in the context of attributes
.yml,.yaml,.json: load as YAML and merge into attrs

All other file types raise an error.



66
67
68
69
70
71
72
73
74
75
76
77
# File 'lib/linecook/attributes.rb', line 66

def load_attrs(path)
  case File.extname(path)
  when '.rb'
    instance_eval(File.read(path), path)
  when '.yml', '.yaml', '.json'
    attrs.merge!(YAML.load_file(path))
  else
    raise "unsupported attributes format: #{path.inspect}"
  end

  self
end

#load_attrs_extnamesObject

A list of file extnames that may be loaded by load_attrs



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

def load_attrs_extnames
  %w{.rb .yml .yaml .json}
end

#to_hashObject

Disables automatic nesting and returns attrs.



80
81
82
# File 'lib/linecook/attributes.rb', line 80

def to_hash
  Attributes.disable_nest_hash(attrs)
end