Class: Docstache::DataScope

Inherits:
Object
  • Object
show all
Defined in:
lib/docstache/data_scope.rb

Instance Method Summary collapse

Constructor Details

#initialize(data, parent = EmptyDataScope.new) ⇒ DataScope

Returns a new instance of DataScope.



4
5
6
7
# File 'lib/docstache/data_scope.rb', line 4

def initialize(data, parent=EmptyDataScope.new)
  @data = data
  @parent = parent
end

Instance Method Details

#get(key, hash: @data, original_key: key, condition: nil) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/docstache/data_scope.rb', line 9

def get(key, hash: @data, original_key: key, condition: nil)
  symbolize_keys!(hash)
  tokens = key.split('.')
  if tokens.length == 1
    if key.match(/(\w+)\[(\d+)\]/)
      result = hash.fetch($1.to_sym) { |key| @parent.get(original_key) }
      if result.respond_to?(:[])
        result = result[$2.to_i]
      end
    else
      result = hash.fetch(key.to_sym) { |key| @parent.get(original_key) }
    end
    if condition.nil? || !result.respond_to?(:select)
      return result
    else
      return result.select { |el| evaluate_condition(condition, el) }
    end
  elsif tokens.length > 1
    key = tokens.shift
    if key.match(/(\w+)\[(\d+)\]/)
      if hash.has_key?($1.to_sym)
        collection = hash.fetch($1.to_sym)
        if collection.respond_to?(:[])
          subhash = collection[$2.to_i]
        else
          subhash = collection
        end
      else
        return @parent.get(original_key)
      end
    else
      if hash.has_key?(key.to_sym)
        subhash = hash.fetch(key.to_sym)
      else
        return @parent.get(original_key)
      end
    end
    return get(tokens.join('.'), hash: subhash, original_key: original_key)
  end
end