Class: ActiveContext::Container

Inherits:
Object
  • Object
show all
Defined in:
lib/activecontext/container.rb

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeContainer

Returns a new instance of Container.



5
6
7
8
# File 'lib/activecontext/container.rb', line 5

def initialize
  @names = {}
  @contexts = {}
end

Class Method Details

.currentObject



58
59
60
# File 'lib/activecontext/container.rb', line 58

def self.current
  Thread.current[:contextualize]
end

Instance Method Details

#[](key) ⇒ Object



38
39
40
41
42
43
44
# File 'lib/activecontext/container.rb', line 38

def [](key)
  if @names.key?(key)
    self.context(@names[key])[key]
  else
    raise "unknown name #{key}"
  end
end

#[]=(key, value) ⇒ Object



30
31
32
33
34
35
36
# File 'lib/activecontext/container.rb', line 30

def []=(key, value)
  if @names.key?(key)
    self.context(@names[key])[key] = value
  else
    raise "unknown name #{key}"
  end
end

#context(name) {|| ... } ⇒ Object

Yields:

  • ()


62
63
64
65
# File 'lib/activecontext/container.rb', line 62

def context(name)
  yield(@contexts[name]) if block_given?
  @contexts[name]
end

#register(name, storage, &block) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/activecontext/container.rb', line 10

def register(name, storage, &block)
  raise "invalid context name" if methods.include?(name)
  raise "invalid storage" unless storage.respond_to?(:"[]") && storage.respond_to?(:"[]=")
  
  @contexts[name] = Context.new(storage)

  eigen = class << self; self; end
  eigen.send(:define_method, name) do |*args, &block2|
    raise "#{name} #{args.first} already exist" if @names.key?(args.first)
    @names[args.first] = name
    
    if args.length > 1
      raise "pass either a block or value. not both." if block2
      self[args.first] = args[1]
    end
    
    self[args.first] = block2 if block2
  end
end

#run(&block) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
# File 'lib/activecontext/container.rb', line 46

def run(&block)
  c = Thread.current[:contextualize]
  raise "found existing container" if c && c != self

  begin
    Thread.current[:contextualize] = self
    block.call
  ensure
    Thread.current[:contextualize] = nil
  end unless c
end