Class: ActiveContext::Container
- Inherits:
-
Object
- Object
- ActiveContext::Container
- Defined in:
- lib/activecontext/container.rb
Class Method Summary collapse
Instance Method Summary collapse
- #[](key) ⇒ Object
- #[]=(key, value) ⇒ Object
- #context(name) ⇒ Object
-
#initialize ⇒ Container
constructor
A new instance of Container.
- #register(name, ctx = {}, &block) ⇒ Object
- #run(&block) ⇒ Object
Constructor Details
#initialize ⇒ Container
Returns a new instance of Container.
3 4 5 |
# File 'lib/activecontext/container.rb', line 3 def initialize @names = {} end |
Class Method Details
.current ⇒ Object
53 54 55 |
# File 'lib/activecontext/container.rb', line 53 def self.current Thread.current[:contextualize] end |
Instance Method Details
#[](key) ⇒ Object
33 34 35 36 37 38 39 |
# File 'lib/activecontext/container.rb', line 33 def [](key) if @names.key?(key) self.context(@names[key])[key] else raise "unknown name #{key}" end end |
#[]=(key, value) ⇒ Object
25 26 27 28 29 30 31 |
# File 'lib/activecontext/container.rb', line 25 def []=(key, value) if @names.key?(key) self.context(@names[key])[key] = value else raise "unknown name #{key}" end end |
#context(name) ⇒ Object
57 58 59 |
# File 'lib/activecontext/container.rb', line 57 def context(name) instance_variable_get("@#{name}") end |
#register(name, ctx = {}, &block) ⇒ Object
7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
# File 'lib/activecontext/container.rb', line 7 def register(name, ctx={}, &block) raise "invalid context name" if methods.include?(name) instance_variable_set("@#{name}", ctx) 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
41 42 43 44 45 46 47 48 49 50 51 |
# File 'lib/activecontext/container.rb', line 41 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 |