简体   繁体   English

如何从Ruby Gem获取项目的目录路径?

[英]From a Ruby Gem, how can I get the directory path to the project?

Suppose I am developing a Ruby gem that will be installed in a project by being added to its gemfile. 假设我正在开发一个Ruby gem,它将通过添加到其gemfile中而安装在项目中。 From my gem, I want to know the root directory path to the project. 从我的宝石,我想知道项目的根目录路径。 How can I get that? 我该怎么办?

If you're using Rails, use Rails.root . 如果您使用的是Rails,请使用Rails.root

If you don't know the 'main project' is Rails... there isn't neccesarily a great way to do it. 如果您不知道“主要项目”是Rails,那么没有必要的绝妙方法。

Global $0 is the command name that the ruby script was invoked with. 全局$0是调用ruby脚本的命令名称。 But this won't neccesarily include a path. 但这并不一定包含路径。 You can try File.expand_path $0 , but there are a very many reasons that would cause this to not give you what you want, including the program may have changed it's "working directory". 您可以尝试File.expand_path $0 ,但是有很多原因会导致它无法满足您的需求,包括程序可能已更改了它的“工作目录”。 Dir.pwd will give you the "current working directory", which may be the directory of the "project" only if the project was invoked from the "project directory" and the code hasn't changed the current working directory. Dir.pwd将为您提供“当前工作目录”,只有在从“项目目录”中调用了项目并且代码未更改当前工作目录的情况下,它才可能是“项目”的目录。

In general, there's actually no build-in notion of a "project" or "project directory" in ruby -- you can have a ruby script that isn't really part of a project at all, it's just a file living wherever in the file system you want. 通常,在ruby中实际上没有“项目”或“项目目录”的内置概念-您可以拥有一个ruby脚本,它根本不是项目的一部分,它只是文件存在于目录中的任何位置。您想要的文件系统。

I don't think there's a general reliable way to do this, it depends on how "the project" was set up, which of course a gem can't be sure of. 我认为没有通用的可靠方法来执行此操作,这取决于“项目”的设置方式,当然,这是无法确定的。

But if you're using Rails, Rails.root , because Rails has conventions for how it's set up and invoked, and implements the feature Rails.root in it's startup processes to record the Rails 'project directory'. 但是,如果您使用的是Rails,请使用Rails.root ,因为Rails具有如何设置和调用约定,并在启动过程中实现了Rails.root功能来记录Rails的“项目目录”。

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 . 如果定义了Rails,则使用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). 如果定义了Bundler,我们将使用Bundler.root但是只有在项目根目录下定义了Gemfile时,它才有效(在大多数情况下是这样)。 Else fallback to Dir.pwd 其他回Dir.pwd

def project_root
  if defined?(Rails)
    return Rails.root
  end

  if defined?(Bundler)
    return Bundler.root
  end

  Dir.pwd
end

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM