Class: Tanuki::Context
Overview
Tanuki::Context is used to create unique environments for each request. Child contexts inherit parent context entries and can override them without modifying the parent context. Use Tanuki::Context::child to create new contexts.
Class Method Summary collapse
-
.child ⇒ Object
Creates and returns child context object.
-
.inspect ⇒ Object
Returns a printable version of Tanuki::Context, represented as a
Hash. -
.method_missing(sym, arg = nil) ⇒ Object
Allowes arbitary values to be assigned to context with a
key=method. -
.new ⇒ Object
Disallow context instantiation.
Class Method Details
.child ⇒ Object
Creates and returns child context object. This object’s superclass is going to be current context class.
14 15 16 17 18 |
# File 'lib/tanuki/context.rb', line 14 def child child = Class.new(self) child.instance_variable_set(:@_defined, {}) child end |
.inspect ⇒ Object
Returns a printable version of Tanuki::Context, represented as a Hash. Can be used during development for inspection purposes. – When changing this method, remember to update ‘#+ 12’ to ‘defined.inspect` line number. This is required to avoid infinite recursion.
25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 |
# File 'lib/tanuki/context.rb', line 25 def inspect return to_s if caller.any? {|entry_point| entry_point =~ /\A#{__FILE__}:#{__LINE__ + 12}/} defined = {} ancestors.each do |ancestor| ancestor.instance_variable_get(:@_defined).each_key do |key| begin defined[key] ||= send(key) rescue ArgumentError defined[key] ||= method(key) end end break if ancestor.equal? Context end defined.inspect end |
.method_missing(sym, arg = nil) ⇒ Object
Allowes arbitary values to be assigned to context with a key= method. A reader in context object class is created for each assigned value.
43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 |
# File 'lib/tanuki/context.rb', line 43 def method_missing(sym, arg=nil) match = sym.to_s.match(/\A(?!(?:child|inspect|method_missing)=\Z)([^=]+)(=)?\Z/) raise "`#{sym}' method cannot be called for Context and its descendants" unless match defined = @_defined class << self; self; end.instance_eval do method_sym = match[1].to_sym if defined.include? method_sym undef_method method_sym else defined[method_sym] = nil end if arg.is_a? Proc define_method(method_sym, &arg) else define_method(method_sym) { arg } end return arg end if match[2] super end |
.new ⇒ Object
Disallow context instantiation
65 66 67 |
# File 'lib/tanuki/context.rb', line 65 def new raise "contexts cannot be instantiated" end |