寻找宝石根 [英] Finding the gem root
本文介绍了寻找宝石根的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
有没有办法知道我的 gem 的根路径?我正在尝试从 gems 路径中的 yaml 加载默认配置.如何使用 ruby 获取 gems 根目录?
Is there a way to know the root path of my gem? I am trying to load a default config from a yaml inside the gems path. How do I get the gems root directory with ruby?
推荐答案
给定以下项目结构:
your_gem/
lib/
your_gem.rb
我会这样做:
# your_gem.rb
module YourGem
def self.root
File.expand_path '../..', __FILE__
end
end
Ruby 2.0 引入了 内核#__dir__
方法;它可以实现更短的解决方案:
Ruby 2.0 introduced the Kernel#__dir__
method; it enables a considerably shorter solution:
# your_gem.rb
module YourGem
def self.root
File.dirname __dir__
end
end
如果您需要访问其他目录,您可以简单地在 root
上构建:
If you need access to the other directories, you can simply build upon root
:
module YourGem
def self.bin
File.join root, 'bin'
end
def self.lib
File.join root, 'lib'
end
end
这篇关于寻找宝石根的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文