Sha256: 0cfa3c9b5a3426fc3b364b793a8178bd6ce47ac724c175e0eee11afb80c15ea4

Contents?: true

Size: 1.7 KB

Versions: 10

Compression:

Stored size: 1.7 KB

Contents

require 'astrails/safe/config/builder'
module Astrails
  module Safe
    module Config
      class Node
        attr_reader :parent
        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

        # looks for the path from this node DOWN. will not delegate to parent
        def get(*path)
          key = path.shift
          value = @data[key.to_s]
          return value if value && path.empty?

          value && value.get(*path)
        end

        # recursive find
        # starts at the node and continues to the parent
        def find(*path)
          get(*path) || @parent && @parent.find(*path)
        end
        alias :[] :find

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

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

        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

        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

      end
    end
  end
end

Version data entries

10 entries across 10 versions & 4 rubygems

Version Path
astrails-safe-0.1.1 lib/astrails/safe/config/node.rb
astrails-safe-0.1.2 lib/astrails/safe/config/node.rb
astrails-safe-0.1.3 lib/astrails/safe/config/node.rb
astrails-safe-0.1.4 lib/astrails/safe/config/node.rb
astrails-safe-0.1.6 lib/astrails/safe/config/node.rb
colin-safe-0.1.6 lib/astrails/safe/config/node.rb
colin-safe-0.1.7 lib/astrails/safe/config/node.rb
colin-safe-0.1.8 lib/astrails/safe/config/node.rb
markmansour-safe-0.1.7 lib/astrails/safe/config/node.rb
ralph-safe-0.1.7 lib/astrails/safe/config/node.rb