我正在创建一个 gem,我想在其中定义一些可用的常量。
在我实际的gemspec
中,我添加了以下内容:
config = File.expand_path('../config', __FILE__)
$LOAD_PATH.unshift(config) unless $LOAD_PATH.include?(config)
require 'constants.rb'
在constants.rb
中,我定义了一个简单的变量:$FOO = "Hello, World!"
然后在我的 lib/gem_name/core.rb
中,我尝试放置 $FOO
但它似乎不可用。没有错误,只是显示空白。我是否不明白 gem 依赖项和 require 树在这里是如何工作的?
** 更新 **
我还尝试直接在 LOAD_PATH 中的 lib
下面添加一个 config
目录。然后在我的库中,我尝试require config/constants
,但这意味着它无法加载这样的文件。
我还尝试直接将 constants.rb
移动到 lib 目录并要求这样做,它警告我它无法加载此类文件。有些东西非常不稳定。
最佳答案
根据Katz ,
When your gem is built, Rubygems will run that code and create a static representation. This means it’s fine to pull your gem’s version or other shared details out of your library itself. Do not, however, use other libraries or dependencies.
这意味着在构建 gem 时会运行 require 'constants.rb'
和 $LOAD_PATH.unshift(...)
等。在运行时,它不会更改 $LOAD_PATH
或导致全局需求。使用gem.require_paths
而不是在运行时修改 $LOAD_PATH
。
例如,在您的 gemspec 中,使用
gem.files += Dir['config/**/*']
gem.require_paths = %w[lib config]
然后在需要$FOO
的地方,使用
require 'constants'
附注
- 使用
require
时,无需包含.rb
扩展名。 - 确保您需要的所有文件都位于
gem.files
中.
关于ruby - 使配置可通过整个 ruby gem,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/18214998/