class TappingDevice::MethodHijacker

Attributes

target[R]

Public Class Methods

new(target) click to toggle source
# File lib/tapping_device/method_hijacker.rb, line 5
def initialize(target)
  @target = target
end

Public Instance Methods

hijack_methods!() click to toggle source
# File lib/tapping_device/method_hijacker.rb, line 9
def hijack_methods!
  target.methods.each do |method_name|
    if is_writer_method?(method_name)
      redefine_writer_method!(method_name)
    elsif is_reader_method?(method_name)
      redefine_reader_method!(method_name)
    end
  end
end

Private Instance Methods

has_definition_source?(method_name) click to toggle source
# File lib/tapping_device/method_hijacker.rb, line 33
def has_definition_source?(method_name)
  target.method(method_name).source_location
end
is_reader_method?(method_name) click to toggle source
# File lib/tapping_device/method_hijacker.rb, line 27
def is_reader_method?(method_name)
  has_definition_source?(method_name) && target.method(method_name).source.match?(/attr_reader|attr_accessor/)
rescue MethodSource::SourceNotFoundError
  false
end
is_writer_method?(method_name) click to toggle source
# File lib/tapping_device/method_hijacker.rb, line 21
def is_writer_method?(method_name)
  has_definition_source?(method_name) && method_name.match?(/\w+=/) && target.method(method_name).source.match?(/attr_writer|attr_accessor/)
rescue MethodSource::SourceNotFoundError
  false
end
redefine_reader_method!(method_name) click to toggle source
# File lib/tapping_device/method_hijacker.rb, line 47
    def redefine_reader_method!(method_name)
      target.instance_eval <<-RUBY, __FILE__, __LINE__ + 1
        def #{method_name}
          @#{method_name}
        end
      RUBY
    end
redefine_writer_method!(method_name) click to toggle source
# File lib/tapping_device/method_hijacker.rb, line 37
    def redefine_writer_method!(method_name)
      ivar_name = "@#{method_name.to_s.sub("=", "")}"

      target.instance_eval <<-RUBY, __FILE__, __LINE__ + 1
        def #{method_name}(val)
          #{ivar_name} = val
        end
      RUBY
    end