module Benchmeth::ClassMethods

Public Instance Methods

benchmark(*method_names) click to toggle source
# File lib/benchmeth.rb, line 25
def benchmark(*method_names)
  method_names.each do |method_name|
    method_name = method_name.to_sym
    send :alias_method, :"#{method_name}_without_benchmark", method_name
    send :define_method, method_name do |*args, &block|
      method_prefix =
        case self
        when $benchmeth_main
          ""
        when Class
          "#{name}."
        else
          "#{self.class.name}#"
        end

      if Benchmeth.use_notifications
        payload = {
          name: "#{method_prefix}#{method_name}"
        }
        ActiveSupport::Notifications.instrument "benchmark.benchmeth", payload do
          send(:"#{method_name}_without_benchmark", *args, &block)
        end
      else
        start_time = Time.now
        result = send(:"#{method_name}_without_benchmark", *args, &block)
        realtime = Time.now - start_time
        Benchmeth.on_benchmark.call("#{method_prefix}#{method_name}", realtime)
        result
      end
    end
  end
end