lib/bumbler/hooks.rb in bumbler-0.5.0 vs lib/bumbler/hooks.rb in bumbler-0.6.0

- old
+ new

@@ -1,20 +1,17 @@ +# frozen_string_literal: true module Bumbler module Hooks @slow_threshold = 100.0 - @previous_gems = {} + @started_items = {} @slow_requires = {} # Everything's a class method (we're a singleton) class << self - def slow_threshold=(time) - @slow_threshold = time - end + attr_writer :slow_threshold - def slow_requires - @slow_requires - end + attr_reader :slow_requires # Inject our custom handling of require into the Kernel. def hook_require! @hooking_require = true @@ -27,11 +24,11 @@ orig_public_require.call(path, *args) end end end - orig_instance_require = self.instance_method(:require) + orig_instance_require = instance_method(:require) define_method(:require) do |path, *args| ::Bumbler::Hooks.handle_require(path) do orig_instance_require.bind(self).call(path, *args) end end @@ -42,11 +39,11 @@ # Even better: Other gems hook require as well. The instance method one at least. def watch_require! ::Kernel.module_eval do # It isn't previously defined in Kernel. This could be a bit dangerous, though. - def self.method_added(method_name, *args) + def self.method_added(method_name, *_args) if method_name == :require && !::Bumbler::Hooks.hooking_require? # Fix those hooks. ::Bumbler::Hooks.hook_require! end end @@ -57,34 +54,34 @@ @hooking_require end # Actually do something about a require here. def handle_require(path, &block) - # break out early if we're already handling this + # break out early if we're already handling the path return yield if path == @previous_require @previous_require = path - # Shortcut unless we're tracking the gem - gem_name = Bumbler::Bundler.gem_for_require(path) - return yield unless gem_name + # ignore untracked gem + return yield unless (gem_name = Bumbler::Bundler.gem_for_require(path)) - # Track load starts - Bumbler::Bundler.require_started(path) unless @previous_gems[gem_name] - @previous_gems[gem_name] = true + # track load starts + Bumbler::Bundler.require_started(gem_name) unless @started_items[gem_name] + @started_items[gem_name] = true time, result = benchmark(path, &block) - Bumbler::Bundler.require_finished(path, time) if result + # TODO: for items with multiple paths we need to add the times + Bumbler::Bundler.require_finished(gem_name, path, time) if result result end def benchmark(key) - start = Time.now.to_f + start = Process.clock_gettime(Process::CLOCK_MONOTONIC) result = yield - time = (Time.now.to_f - start) * 1000 # ms + time = (Process.clock_gettime(Process::CLOCK_MONOTONIC) - start) * 1000 # ms @slow_requires[key] = time if time > @slow_threshold - return time, result + [time, result] end end end end