Suppose I am developing a Ruby gem that will be installed in a project by being added to its Gemfile. From my gem, I want to know the directory path to the installer project's root. How can I get that?
There is no perfect solution to this problem but you could create a fallback based solution that would work in most general cases. If Rails is defined, we use Rails.root
. If Bundler is defined, we use the Bundler.root
but it would only work when the Gemfile is defined at the project root (which is true in most cases). Else fallback to Dir.pwd
def project_root
if defined?(Rails)
return Rails.root
end
if defined?(Bundler)
return Bundler.root
end
Dir.pwd
end