TAGS :Viewed: 2 - Published at: a few seconds ago

[ Handling require in a project meant to be provided as a gem ]

I'm completely lost with ruby "require" (and I don't have the option for require_relative since my code is meant to run with ruby 1.8.7.

First some sample code.

requester.rb

require './column/main_column'

....

column/main_column.rb

require './helper' # helper.rb being in the root dir

....

column/segment_column

require './column/main_column'
require './helper' # helper.rb being in the root dir

....

I'm completely lost in how should I use my requires to make my code usable inside a gem and in a standalone way (without assuming a previous gem installation). I was reading at Jekyll's code and every dependencies seems to be loaded in the main rb file which to my opinion is a bit dirty and still do resolve the problem if column/segment_column.rb needs to be called independently.

Please try to argument about different approaches and why one is the best.

Answer 1


You should require files without the extension and relative to your gem project's lib folder.

For example, given this structure:

example-gem/
  lib/
    example/
      gem.rb
    example.rb
  example-gem.gemspec

You'd require the main example module using:

require 'example'

And in the example.rb file you'd find:

require 'example/gem'

This set of conventions is adopted by the community and is documented on the RubyGems Guides. If they fail, it is often because your gem's lib directory is not in Ruby's $LOAD_PATH, which usually means the gem is not installed.

Building and installing gems during development is cumbersome. For that reason, gems like Bundler became part of the toolboxes of many Rubyists. Bundler lets you use your gem without having to build or install it locally. You can simply bundle exec a script that uses your gem or use bundle console in order to interact with it.