Class: Fakes::ClassSwap
- Inherits:
-
Object
- Object
- Fakes::ClassSwap
- Defined in:
- lib/fakes/class_swap.rb
Instance Attribute Summary collapse
-
#klass ⇒ Object
readonly
Returns the value of attribute klass.
-
#original ⇒ Object
Returns the value of attribute original.
-
#replacement ⇒ Object
Returns the value of attribute replacement.
Instance Method Summary collapse
- #get_modules(fully_qualified_klass) ⇒ Object
-
#initialize(fully_qualified_klass, replacement, options = {}) ⇒ ClassSwap
constructor
A new instance of ClassSwap.
- #initiate ⇒ Object
- #reset ⇒ Object
- #swap_to(new_value) {|current| ... } ⇒ Object
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, ={}) 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 = .fetch(:remove_strategy, Proc.new do |klass| class_root.send(:remove_const, klass) end) @set_strategy = .fetch(:set_strategy, Proc.new do |klass, new_value| class_root.const_set(klass.to_sym, new_value) end) end |
Instance Attribute Details
#klass ⇒ Object (readonly)
Returns the value of attribute klass.
4 5 6 |
# File 'lib/fakes/class_swap.rb', line 4 def klass @klass end |
#original ⇒ Object
Returns the value of attribute original.
3 4 5 |
# File 'lib/fakes/class_swap.rb', line 3 def original @original end |
#replacement ⇒ Object
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 |
#initiate ⇒ Object
40 41 42 |
# File 'lib/fakes/class_swap.rb', line 40 def initiate swap_to(replacement){|original| @original = original} end |
#reset ⇒ Object
44 45 46 |
# File 'lib/fakes/class_swap.rb', line 44 def reset swap_to(@original) end |
#swap_to(new_value) {|current| ... } ⇒ Object
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 |