Class: MemoryProfiler::Helpers

Inherits:
Object
  • Object
show all
Defined in:
lib/memory_profiler/helpers.rb

Constant Summary collapse

KERNEL_CLASS_METHOD =
Kernel.instance_method(:class)

Instance Method Summary collapse

Constructor Details

#initializeHelpers

Returns a new instance of Helpers.


6
7
8
9
10
11
# File 'lib/memory_profiler/helpers.rb', line 6

def initialize
  @gem_guess_cache = Hash.new
  @location_cache = Hash.new { |h, k| h[k] = Hash.new.compare_by_identity }
  @class_name_cache = Hash.new.compare_by_identity
  @string_cache = Hash.new
end

Instance Method Details

#guess_gem(path) ⇒ Object


13
14
15
16
17
18
19
20
21
22
23
24
25
26
# File 'lib/memory_profiler/helpers.rb', line 13

def guess_gem(path)
  @gem_guess_cache[path] ||=
    if /(\/gems\/.*)*\/gems\/(?<gemname>[^\/]+)/ =~ path
      gemname
    elsif /\/rubygems[\.\/]/ =~ path
      "rubygems"
    elsif /ruby\/2\.[^\/]+\/(?<stdlib>[^\/\.]+)/ =~ path
      stdlib
    elsif /(?<app>[^\/]+\/(bin|app|lib))/ =~ path
      app
    else
      "other"
    end
end

#lookup_class_name(klass) ⇒ Object


54
55
56
# File 'lib/memory_profiler/helpers.rb', line 54

def lookup_class_name(klass)
  ((klass.is_a?(Class) && klass.name) || '<<Unknown>>').to_s
end

#lookup_location(file, line) ⇒ Object


28
29
30
# File 'lib/memory_profiler/helpers.rb', line 28

def lookup_location(file, line)
  @location_cache[file][line] ||= "#{file}:#{line}"
end

#lookup_string(obj) ⇒ Object


63
64
65
66
67
68
# File 'lib/memory_profiler/helpers.rb', line 63

def lookup_string(obj)
  # This string is shortened to 200 characters which is what the string report shows
  # The string report can still list unique strings longer than 200 characters
  #   separately because the object_id of the shortened string will be different
  @string_cache[obj] ||= String.new << obj[0, 200]
end

#object_class(obj) ⇒ Object


34
35
36
37
38
39
40
41
# File 'lib/memory_profiler/helpers.rb', line 34

def object_class(obj)
  klass = obj.class rescue nil
  unless Class === klass
    # attempt to determine the true Class when .class returns something other than a Class
    klass = KERNEL_CLASS_METHOD.bind_call(obj)
  end
  klass
end