Question

I am creating a gem where I'd like to define some constants to be available.

In my actual gemspec, I added the following:

config = File.expand_path('../config', __FILE__)
$LOAD_PATH.unshift(config) unless $LOAD_PATH.include?(config)

require 'constants.rb'

In constants.rb I have a simple var defined: $FOO = "Hello, World!"

Then in my lib/gem_name/core.rb, I'm attempting to puts $FOO but it doesn't seem to be available. No error, just comes up blank. Am I not understanding how gem dependencies and the require tree works here?

** UPDATE **

I have also tried just adding a config directory directly underneath lib which is in the LOAD_PATH already. then in my library, I am attempting to require config/constants, but that's saying it cannot load such a file.

I have also tried just moving constants.rb to the lib directory directly and requiring that, and it's warning me that it cannot load such file. Something is terribly wonky.

Was it helpful?

Solution

According to 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.

That means that require 'constants.rb' and $LOAD_PATH.unshift(...) etc are run when you build the gem. At runtime, it doesn't change the $LOAD_PATH or cause a global require. Use gem.require_paths instead to modify $LOAD_PATH at runtime.

For example, in your gemspec, use

gem.files += Dir['config/**/*']
gem.require_paths = %w[lib config]

Then in places where $FOO is required, use

require 'constants'

Side Notes

  • You don't need to include the .rb extension when using require.
  • Make sure all the files you need are in gem.files.
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top