Sha256: 86aeeb21c75b2e270281f8fa71d17dc76d4ca0539eb8ee495aa3a454be6bb45f

Contents?: true

Size: 1.62 KB

Versions: 1

Compression:

Stored size: 1.62 KB

Contents

module Warp
  class Instrument
    class << self
      def for(klass, method)
        @@registry ||= {}
        @@registry[klass] ||= {}
        @@registry[klass][method] || new(klass, method)
      end

      private

      def register(instrument)
        @@registry ||= {}
        @@registry[instrument.klass] ||= {}
        @@registry[instrument.klass][instrument.method] = instrument        
      end
    end

    attr_accessor :klass, :method, :hook, :enabled, :calls

    def initialize(klass, method)
      self.klass = klass
      self.method = method
      self.enabled = false
      self.calls = []
      setup_hook

      self.class.send(:register, self)
    end

    def run
      enable
      yield
      disable
    end

    def enabled?
      enabled
    end

    def log(args)
      calls << args
    end

    private

    def enable
      self.enabled = true
    end

    def disable
      self.enabled = false
    end

    def setup_hook
      if Module.method_defined?(:prepend)
        self.hook = Module.new

        hook.send(:define_method, method) do |*args|
          if Warp::Instrument.for(self.class, __method__).enabled?
            Warp::Instrument.for(self.class, __method__).log(args)
          end

          super(*args)
        end

        klass.prepend(hook)
      else
        original_method = klass.instance_method(method)

        klass.send(:define_method, method) do |*args|
          if Warp::Instrument.for(self.class, __method__).enabled?
            Warp::Instrument.for(self.class, __method__).log(args)
          end

          original_method.bind(self).call(*args)
        end
      end
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
warp-1.3.0 lib/warp/instrument.rb