Sha256: b41a13ab98e3ab6c6f574d8a5e02851383c3dbb9416ac2f49c3836c374f70acf

Contents?: true

Size: 868 Bytes

Versions: 2

Compression:

Stored size: 868 Bytes

Contents

require_relative 'nodifier'
require 'active_support/core_ext/hash'

module ConceptQL
  class Tree
    attr :nodifier, :behavior
    def initialize(opts = {})
      @nodifier = opts.fetch(:nodifier, Nodifier.new)
      @behavior = opts.fetch(:behavior, nil)
    end

    def root(*queries)
      @root ||= traverse(queries.flatten.map(&:statement).flatten.map(&:deep_symbolize_keys))
    end

    private
    def traverse(obj)
      case obj
      when Hash
        if obj.keys.length > 1
          obj = Hash[obj.map { |key, value| [ key, traverse(value) ]}]
          return obj
        end
        type = obj.keys.first
        values = traverse(obj[type])
        obj = nodifier.create(type, values)
        obj.extend(behavior) if behavior
        obj
      when Array
        obj.map { |value| traverse(value) }
      else
        obj
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
conceptql-0.0.5 lib/conceptql/tree.rb
conceptql-0.0.4 lib/conceptql/tree.rb