Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ruby: How to deduce the "current" gem name?

I'm aware of the following to grab a Gem's specification for interrogation:

spec = Gem::Specification.find_by_name('my_gem')

Is there a way to programmatically identify "this" gem's name such that the above could be rewritten in a reusable manner?

In other words, how can you get the parent gem's name from some executing Ruby code at runtime?

like image 432
KomodoDave Avatar asked Dec 13 '12 12:12

KomodoDave


1 Answers

To find the gem specification for the current source file (assuming it's a source file in the lib dir):

require 'rubygems'

searcher = if Gem::Specification.respond_to? :find
  # ruby 2.0
  Gem::Specification
elsif Gem.respond_to? :searcher
  # ruby 1.8/1.9
  Gem.searcher.init_gemspecs
end
spec = unless searcher.nil?
  searcher.find do |spec|
    File.fnmatch(File.join(spec.full_gem_path,'*'), __FILE__)
  end
end

You could make this reusable by passing in the __FILE__ from the source file you're actually interested in, or by examining the caller stack (but that's probably a bad idea).

like image 75
Jacob Lukas Avatar answered Sep 29 '22 21:09

Jacob Lukas