Class: Garner::Strategies::Context::Key::Caller

Inherits:
Base
  • Object
show all
Defined in:
lib/garner/strategies/context/key/caller.rb

Class Method Summary collapse

Class Method Details

.apply(identity, ruby_context = nil) ⇒ Garner::Cache::Identity

Injects the caller’s location into the key hash.

Parameters:

  • identity (Garner::Cache::Identity)

    The cache identity.

  • ruby_context (Object) (defaults to: nil)

    An optional Ruby context.

Returns:



38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
# File 'lib/garner/strategies/context/key/caller.rb', line 38

def self.apply(identity, ruby_context = nil)
  value = nil

  if ruby_context.send(:caller)
    ruby_context.send(:caller).compact.each do |line|
      parts = line.match(/(?<filename>[^:]+)\:(?<lineno>[^:]+)/)
      file = (Pathname.new(parts[:filename]).realpath.to_s rescue nil)
      next if file.nil? || file == ''
      next if file.include?(File.join('lib', 'garner'))

      if (root = Garner.config.caller_root)
        root += File::SEPARATOR unless root[-1] == File::SEPARATOR
        next unless file =~ /^#{root}/
        value = "#{file.gsub(root || '', '')}:#{parts[:lineno]}"
      else
        value = "#{file}:#{parts[:lineno]}"
      end

      break
    end
  end

  value ? identity.key(field => value) : super
end

.default_rootString

Determine the most likely root path for the current Garner client application. If in a Rails application, Rails.root is used. Otherwise, the nearest ancestor directory containing a Gemfile is used.

Returns:

  • (String)

    The default root path.

See Also:



18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/garner/strategies/context/key/caller.rb', line 18

def self.default_root
  if defined?(::Rails) && ::Rails.respond_to?(:root)
    ::Rails.root.realpath.to_s
  else
    # Try to use the nearest ancestor directory containing a Gemfile.
    requiring_caller = send(:caller).find do |line|
      !line.include?(File.join('lib', 'garner'))
    end
    return nil unless requiring_caller

    requiring_file = requiring_caller.split(':')[0]
    gemfile_root(File.dirname(requiring_file))
  end
end

.fieldObject



6
7
8
# File 'lib/garner/strategies/context/key/caller.rb', line 6

def self.field
  :caller
end

.gemfile_root(path) ⇒ Object



63
64
65
66
67
68
69
70
71
72
73
74
75
# File 'lib/garner/strategies/context/key/caller.rb', line 63

def self.gemfile_root(path)
  path = Pathname.new(path).realpath.to_s
  newpath = Pathname.new(File.join(path, '..')).realpath.to_s
  if newpath == path
    # We've reached the filesystem root; return
    return nil
  elsif File.exist?(File.join(newpath, 'Gemfile'))
    # We've struck Gemfile gold; return current path
    return newpath
  else
    return gemfile_root(newpath)
  end
end