Class: Hijacker

Inherits:
Object show all
Defined in:
lib/hijacker.rb

Overview

Hijacker class

This class is used by RoleRequirementTestHelper to temporarily hijack a controller action for testing

It can be used for other tests as well.

You can contract the author with questions

Tim C. Harper - irb(main):001:0> ( 'tim_see_harperATgmail._see_om'.gsub('_see_', 'c').gsub('AT', '@') )

Example usage:

hijacker = Hijacker.new(ListingsController)
hijacker.hijack_instance_method("index", "render :text => 'hello world!'" )
get :index        # will return "hello world"
hijacker.restore  # put things back the way you found it

Instance Method Summary collapse

Constructor Details

#initialize(klass) ⇒ Hijacker

Returns a new instance of Hijacker.



18
19
20
21
# File 'lib/hijacker.rb', line 18

def initialize(klass)
  @target_klass = klass
  @method_stores = {}
end

Instance Method Details

#hijack_class_method(method_name, eval_string = nil, arg_names = [], &block) ⇒ Object



23
24
25
# File 'lib/hijacker.rb', line 23

def hijack_class_method(method_name, eval_string = nil, arg_names = [], &block)
  hijack_method(class_self_instance, method_name, eval_string, arg_names, &block )
end

#hijack_instance_method(method_name, eval_string = nil, arg_names = [], &block) ⇒ Object



27
28
29
# File 'lib/hijacker.rb', line 27

def hijack_instance_method(method_name, eval_string = nil, arg_names = [], &block)
  hijack_method(@target_klass, method_name, eval_string, arg_names, &block )
end

#restoreObject

restore all



32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/hijacker.rb', line 32

def restore
  @method_stores.each_pair{|klass, method_stores|
    method_stores.reverse_each{ |method_name, method| 
      klass.send :undef_method, method_name
      klass.send :define_method, method_name, method if method
    }
  }
  @method_stores.clear
  true
rescue
  false
end