Class: Minicontext::Context

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

Constant Summary collapse

KEYWORD =
%i(before after)
COMPOSE =
-> (f, g) { -> (env) { f.(g.(env)) } }
RELAY =
-> (env) { env }

Instance Method Summary collapse

Constructor Details

#initialize(parent = nil) ⇒ Context

Returns a new instance of Context.



7
8
9
10
# File 'lib/minicontext/context.rb', line 7

def initialize(parent = nil)
  @vars   = {}
  @parent = parent
end

Instance Method Details

#[](name) ⇒ Object



53
54
55
# File 'lib/minicontext/context.rb', line 53

def [](name)
  router[name]
end

#[]=(name, val) ⇒ Object

Raises:



57
58
59
60
61
# File 'lib/minicontext/context.rb', line 57

def []=(name, val)
  raise AssignError, name if @vars[name]

  @vars[name] = val
end

#action(&block) ⇒ Object



37
38
39
# File 'lib/minicontext/context.rb', line 37

def action(&block)
  instance_eval &block
end

#call(name) ⇒ Object



45
46
47
# File 'lib/minicontext/context.rb', line 45

def call(name)
  Proc === (val = @vars[name]) ? apply(name) : val
end

#context(name, &block) ⇒ Object

Raises:



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

def context(name, &block)
  raise AssignError, name if KEYWORD.include?(name)
  raise AssignError, name if (val = @vars[name]) && Proc === val

  val ? val.action(&block) : define_context(name, &block)
end

#let(name, &block) ⇒ Object

Raises:



23
24
25
26
27
28
29
30
31
# File 'lib/minicontext/context.rb', line 23

def let(name, &block)
  raise AssignError, name if KEYWORD.include?(name)

  self[name] = -> (env) do
    env.memoized.fetch([self, name]) do
      env.memoized[[self, name]] = env.(self, &block)
    end
  end
end

#load(filename) ⇒ Object



41
42
43
# File 'lib/minicontext/context.rb', line 41

def load(filename)
  instance_eval open(filename) {|f| f.read}, filename
end

#lookup(name) ⇒ Object



49
50
51
# File 'lib/minicontext/context.rb', line 49

def lookup(name)
  Proc === (val = @vars[name]) ? val : (@parent && @parent.lookup(name))
end

#task(name, &block) ⇒ Object



19
20
21
# File 'lib/minicontext/context.rb', line 19

def task(name, &block)
  self[name] = -> (env) { env.(self, &block) }
end