Class: Alula::Context

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

Instance Method Summary collapse

Constructor Details

#initialize(default = {}) ⇒ Context

Returns a new instance of Context.



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

def initialize(default = {})
  @data = {}
  default.each do |key, value|
    @data[key.to_s] = value
  end
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

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



42
43
44
45
46
47
48
49
50
# File 'lib/alula/context.rb', line 42

def method_missing(meth, *args, &block)
  if meth.to_s =~ /=$/
    self.send(:[]=, meth.to_s[0..-2], *args)
  elsif @data.key?(meth.to_s)
    self.send(:[], meth.to_s)
  else
    nil
  end
end

Instance Method Details

#[](key) ⇒ Object



20
21
22
23
24
25
26
# File 'lib/alula/context.rb', line 20

def [](key)
  key = key.to_s
  if @data[key].kind_of?(Hash)
    @data[key] = Context.new @data[key]
  end
  @data[key]
end

#[]=(key, value) ⇒ Object



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

def []=(key, value)
  key = key.to_s
  if value.kind_of?(Hash)
    value = Context.new value
  end
  @data[key] = value
end

#data=(new_data) ⇒ Object



28
29
30
# File 'lib/alula/context.rb', line 28

def data=(new_data)
  @data = new_data
end

#respond_to?(name, include_private = false) ⇒ Boolean

Returns:

  • (Boolean)


32
33
34
35
36
37
38
39
40
# File 'lib/alula/context.rb', line 32

def respond_to?(name, include_private=false)
  if name.to_s =~ /=$/ and @data.key?(name.to_s[0..-2])
    true
  elsif @data.key?(name)
    true
  else
    super
  end
end

#to_liquidObject



52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
# File 'lib/alula/context.rb', line 52

def to_liquid
  @liquid ||= begin
    liquid = Liquid::Context.new(
      nil,  # Environments
      nil,  # Outer Scope
      {:proxy => self}, # Registers
      true) # Rethrow errors
    liquid.class.class_eval do
      def method_missing(meth, *args, &blk)
        if registers[:proxy].respond_to?(meth.to_s)
          registers[:proxy].send(meth, *args)
        else
          super
        end
      end
    end
    @liquid = liquid
  end
end