Class: Astrails::Safe::Config::Node

Inherits:
Object
  • Object
show all
Includes:
Enumerable
Defined in:
lib/astrails/safe/config/node.rb

Constant Summary collapse

MULTIVALUES =
%w/skip_tables exclude files/

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(parent = nil, data = {}, &block) ⇒ Node

Returns a new instance of Node.



8
9
10
11
12
# File 'lib/astrails/safe/config/node.rb', line 8

def initialize(parent = nil, data = {}, &block)
  @parent, @data = parent, {}
  data.each { |k, v| self[k] = v }
  Builder.new(self).instance_eval(&block) if block
end

Instance Attribute Details

#dataObject (readonly)

Returns the value of attribute data.



7
8
9
# File 'lib/astrails/safe/config/node.rb', line 7

def data
  @data
end

#parentObject (readonly)

Returns the value of attribute parent.



6
7
8
# File 'lib/astrails/safe/config/node.rb', line 6

def parent
  @parent
end

Instance Method Details

#dump(indent = "") ⇒ Object



63
64
65
66
67
68
69
70
71
72
# File 'lib/astrails/safe/config/node.rb', line 63

def dump(indent = "")
  @data.each do |key, value|
    if value.is_a?(Node)
      puts "#{indent}#{key}:"
      value.dump(indent + "    ")
    else
      puts "#{indent}#{key}: #{value.inspect}"
    end
  end
end

#each(&block) ⇒ Object



50
51
52
# File 'lib/astrails/safe/config/node.rb', line 50

def each(&block)
  @data.each(&block)
end

#find(*path) ⇒ Object Also known as: []

recursive find starts at the node and continues to the parent



25
26
27
# File 'lib/astrails/safe/config/node.rb', line 25

def find(*path)
  get(*path) || @parent && @parent.find(*path)
end

#get(*path) ⇒ Object

looks for the path from this node DOWN. will not delegate to parent



15
16
17
18
19
20
21
# File 'lib/astrails/safe/config/node.rb', line 15

def get(*path)
  key = path.shift
  value = @data[key.to_s]
  return value if value && path.empty?

  value && value.get(*path)
end

#set(key, value, &block) ⇒ Object Also known as: []=



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/astrails/safe/config/node.rb', line 31

def set(key, value, &block)
  if @data[key.to_s]
    raise(ArgumentError, "duplicate value for '#{key}'") if value.is_a?(Hash) || !MULTIVALUES.include?(key.to_s)
  end

  if value.is_a?(Hash)
    @data[key.to_s] = Node.new(self, value, &block)
  else
    raise(ArgumentError, "#{key}: no block supported for simple values") if block
    if @data[key.to_s]
      @data[key.to_s] = @data[key.to_s].to_a + value.to_a
    else
      @data[key.to_s] = value
    end
    value
  end
end

#to_hashObject



55
56
57
58
59
60
61
# File 'lib/astrails/safe/config/node.rb', line 55

def to_hash
  @data.keys.inject({}) do |res, key|
    value = @data[key]
    res[key] = value.is_a?(Node) ? value.to_hash : value
    res
  end
end