Class: Volt::SubContext

Inherits:
Object show all
Defined in:
lib/volt/page/sub_context.rb

Overview

A sub context takes in a hash of local variables that should be available in front of the current context. It basically proxies the local variables first, then failing those proxies the context.

SubContext is also used for the attrs in controllers. You can pass return_nils to have missing values return nil (as in attrs).

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(locals, context = nil, return_nils = false) ⇒ SubContext

Returns a new instance of SubContext.



11
12
13
14
15
# File 'lib/volt/page/sub_context.rb', line 11

def initialize(locals, context = nil, return_nils = false)
  @locals  = locals.stringify_keys
  @context = context
  @return_nils = return_nils
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(method_name, *args, &block) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/volt/page/sub_context.rb', line 21

def method_missing(method_name, *args, &block)
  method_name = method_name.to_s
  if @locals.key?(method_name)
    obj = @locals[method_name]

    # TODORW: Might get a normal proc, flag internal procs
    if obj.is_a?(Proc)
      obj = obj.call(*args)
    end
    return obj
  elsif @return_nils && method_name[-1] != '='
    return nil
  elsif @context
    return @context.send(method_name, *args, &block)
  end

  fail NoMethodError.new("undefined method `#{method_name}' for \"#{inspect}\":#{self.class}")
end

Instance Attribute Details

#localsObject (readonly)

Returns the value of attribute locals.



9
10
11
# File 'lib/volt/page/sub_context.rb', line 9

def locals
  @locals
end

Instance Method Details

#respond_to?(method_name) ⇒ Boolean

Returns:



17
18
19
# File 'lib/volt/page/sub_context.rb', line 17

def respond_to?(method_name)
  !!(@locals[method_name.to_s] || (@context && @context.respond_to?(method_name)))
end