Class: Mustache::Context

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

Overview

A Context represents the context which a Mustache template is executed within. All Mustache tags reference keys in the Context.

Instance Method Summary collapse

Constructor Details

#initialize(mustache) ⇒ Context

Expect to be passed an instance of ‘Mustache`.



16
17
18
19
# File 'lib/mustache/context.rb', line 16

def initialize(mustache)
  @mustache = mustache
  @stack = [@mustache]
end

Instance Method Details

#[](name) ⇒ Object

Alias for ‘fetch`.



47
48
49
# File 'lib/mustache/context.rb', line 47

def [](name)
  fetch(name, nil)
end

#[]=(name, value) ⇒ Object

Can be used to add a value to the context in a hash-like way.

context = “Chris”



42
43
44
# File 'lib/mustache/context.rb', line 42

def []=(name, value)
  push(name => value)
end

#fetch(name, default = :__raise) ⇒ Object

Similar to Hash#fetch, finds a value by ‘name` in the context’s stack. You may specify the default return value by passing a second parameter.

If no second parameter is passed (or raise_on_context_miss is set to true), will raise a ContextMiss exception on miss.



57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/mustache/context.rb', line 57

def fetch(name, default = :__raise)
  @stack.each do |frame|
    hash = frame.respond_to?(:has_key?)

    if hash && frame.has_key?(name)
      return frame[name]
    elsif hash && frame.has_key?(name.to_s)
      return frame[name.to_s]
    elsif !hash && frame.respond_to?(name)
      return frame.__send__(name)
    end
  end

  if default == :__raise || @mustache.raise_on_context_miss?
    raise ContextMiss.new("Can't find #{name} in #{@stack.inspect}")
  else
    default
  end
end

#popObject

Removes the most recently added object from the context’s internal stack.

Returns the Context.



34
35
36
37
# File 'lib/mustache/context.rb', line 34

def pop
  @stack.shift
  self
end

#push(new) ⇒ Object Also known as: update

Adds a new object to the context’s internal stack.

Returns the Context.



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

def push(new)
  @stack.unshift(new)
  self
end