Class: Fakes::ClassSwap

Inherits:
Object
  • Object
show all
Defined in:
lib/fakes/class_swap.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(fully_qualified_klass, replacement, options = {}) ⇒ ClassSwap

Returns a new instance of ClassSwap.



6
7
8
9
10
11
12
13
14
15
# File 'lib/fakes/class_swap.rb', line 6

def initialize(fully_qualified_klass,replacement,options ={})
  klass_parts = fully_qualified_klass.to_s
  parts = klass_parts.split('::')
  the_module = parts.count == 1 ? Object : eval(parts.slice(0,parts.count - 1).join('::'))
  @klass = parts[parts.count - 1].to_s.to_sym

  @replacement = replacement
  @remove_strategy = options.fetch(:remove_strategy,lambda{|klass_symbol| the_module.send(:remove_const,klass_symbol)})
  @set_strategy = options.fetch(:set_strategy,lambda{|klass_symbol,new_value| the_module.const_set(klass_symbol,new_value)})
end

Instance Attribute Details

#klassObject (readonly)

Returns the value of attribute klass.



4
5
6
# File 'lib/fakes/class_swap.rb', line 4

def klass
  @klass
end

#originalObject

Returns the value of attribute original.



3
4
5
# File 'lib/fakes/class_swap.rb', line 3

def original
  @original
end

#replacementObject

Returns the value of attribute replacement.



3
4
5
# File 'lib/fakes/class_swap.rb', line 3

def replacement
  @replacement
end

Instance Method Details

#initiateObject



17
18
19
# File 'lib/fakes/class_swap.rb', line 17

def initiate
  swap_to(replacement){|original| @original = original}
end

#resetObject



21
22
23
# File 'lib/fakes/class_swap.rb', line 21

def reset
  swap_to(@original)
end

#swap_to(new_value) {|current| ... } ⇒ Object

Yields:

  • (current)


25
26
27
28
29
# File 'lib/fakes/class_swap.rb', line 25

def swap_to(new_value,&block)
  current = @remove_strategy.call(@klass)
  yield current if block_given?
  @set_strategy.call(@klass,new_value)
end