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
16
17
18
19
20
21
22
23
# File 'lib/fakes/class_swap.rb', line 6

def initialize(fully_qualified_klass,replacement,options ={})
  modules = get_modules(fully_qualified_klass)
  @klass = modules.keys.last.to_sym

  class_root = modules.keys[modules.keys.count - 2]
  class_root = modules[class_root.to_sym]

  @replacement = replacement

  @remove_strategy = options.fetch(:remove_strategy, Proc.new do |klass| 
    class_root.send(:remove_const, klass)
  end)

  @set_strategy = options.fetch(:set_strategy, Proc.new do |klass, new_value|
    class_root.const_set(klass.to_sym, new_value)
  end)

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

#get_modules(fully_qualified_klass) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/fakes/class_swap.rb', line 25

def get_modules(fully_qualified_klass)
  klass_parts = fully_qualified_klass.to_s.split("::")
  root = Object
  modules = {}
  modules[:Object] = root

  klass_parts.each do |part|
    class_or_module = root.const_get(part.to_sym)
    modules[part.to_sym] = class_or_module
    root = class_or_module
  end

  modules
end

#initiateObject



40
41
42
# File 'lib/fakes/class_swap.rb', line 40

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

#resetObject



44
45
46
# File 'lib/fakes/class_swap.rb', line 44

def reset
  swap_to(@original)
end

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

Yields:

  • (current)


48
49
50
51
52
# File 'lib/fakes/class_swap.rb', line 48

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