Class: Twig::Context

Inherits:
Hash
  • Object
show all
Defined in:
lib/twig/context.rb

Instance Method Summary collapse

Constructor Details

#initialize(initial_context = {}) ⇒ Context

Returns a new instance of Context.



5
6
7
8
9
# File 'lib/twig/context.rb', line 5

def initialize(initial_context = {})
  super()

  merge!(initial_context)
end

Instance Method Details

#[](key) ⇒ Object



40
41
42
# File 'lib/twig/context.rb', line 40

def [](key)
  super(key.to_sym)
end

#[]=(key, value) ⇒ Object



44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/twig/context.rb', line 44

def []=(key, value)
  key = key.to_sym

  if (frame = stack.last)
    if key?(key) && !frame[:replace].key?(key) && !frame[:remove].include?(key)
      frame[:replace][key] = self[key]
    else
      frame[:remove].push(key)
    end
  end

  super
end

#merge(other) ⇒ Object



21
22
23
# File 'lib/twig/context.rb', line 21

def merge(other)
  self.class.new(self).merge!(other)
end

#merge!(other) ⇒ Object



11
12
13
14
15
16
17
18
19
# File 'lib/twig/context.rb', line 11

def merge!(other)
  unless other.class <= Hash
    raise 'Must merge! another Hash'
  end

  other.each do |k, v|
    self[k] = v
  end
end

#pop_stackObject



29
30
31
32
33
34
35
36
37
38
# File 'lib/twig/context.rb', line 29

def pop_stack
  return unless stack.last

  frame = stack.pop

  frame[:remove].each do |k|
    delete(k)
  end
  frame[:replace].each { |k, v| self[k] = v }
end

#push_stackObject



25
26
27
# File 'lib/twig/context.rb', line 25

def push_stack
  stack.push({ remove: [], replace: {} })
end