Class: DynaMo::Contexts

Inherits:
BasicObject
Defined in:
lib/dyna_mo/contexts.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(mod_name, default_context_name) ⇒ Contexts

Returns a new instance of Contexts.



8
9
10
11
12
13
14
15
# File 'lib/dyna_mo/contexts.rb', line 8

def initialize(mod_name, default_context_name)
  # mod_name MUST be string here to assure target module_name consistency
  @module_name = (mod_name =~ /^::/ ? mod_name : '::' + mod_name)
  @default_context_name = default_context_name.to_sym

  @instance_method_mods = []
  @class_method_mods = []
end

Instance Attribute Details

#default_context_nameObject

Returns the value of attribute default_context_name.



6
7
8
# File 'lib/dyna_mo/contexts.rb', line 6

def default_context_name
  @default_context_name
end

#module_nameObject (readonly)

Returns the value of attribute module_name.



5
6
7
# File 'lib/dyna_mo/contexts.rb', line 5

def module_name
  @module_name
end

Instance Method Details

#__apply__Object



17
18
19
20
21
22
23
24
25
# File 'lib/dyna_mo/contexts.rb', line 17

def __apply__
  target = ::Kernel.eval(@module_name)

  # reverse: Last defined context's method priority is highest
  target.prepend( *(@instance_method_mods.reverse.map(&:applied_module)) )
  (class << target; self; end).prepend( *(@class_method_mods.reverse.map(&:applied_module)) )

  # prepending twice has no effects
end

#def_class_method(method_name, context_name = @default_context_name, &block) ⇒ Object



35
36
37
38
39
40
# File 'lib/dyna_mo/contexts.rb', line 35

def def_class_method(method_name, context_name = @default_context_name, &block)
  raise "block is not given for def_singleton_method" unless block #_given?

  @class_method_mods.push OverrideMethod.new(context_name.to_sym, method_name, &block)
  method_name
end

#def_instance_method(method_name, context_name = @default_context_name, &block) ⇒ Object Also known as: def_method



27
28
29
30
31
32
# File 'lib/dyna_mo/contexts.rb', line 27

def def_instance_method(method_name, context_name = @default_context_name, &block)
  raise "block is not given for def_instance_method" unless block # block_given?

  @instance_method_mods.push OverrideMethod.new(context_name.to_sym, method_name, &block)
  method_name
end