Skip to content

Instantly share code, notes, and snippets.

@lroggendorff
Created October 17, 2012 22:11
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save lroggendorff/3908654 to your computer and use it in GitHub Desktop.
Save lroggendorff/3908654 to your computer and use it in GitHub Desktop.
Local Gem Development $LOAD_PATH Shinanigans

Use bundle gem gemname to generate your gem's doc structure:

.
├── Gemfile
├── LICENSE.txt
├── README.md
├── Rakefile
├── gemname.gemspec
├── lib
│   ├── gemname
│   │   └── version.rb
│   └── gemname.rb

Add a bin directory and put your executable there.

.
├── bin
│   └── gemname

Presumably, your executable will require your gem, but then if you run it like ruby bin/gemname, require will look for an installed gem, not the one in your lib directory.

To address this, add the following before any require statements in your executable:

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

It took me way too long to figure this out, until I realized what that little piece of code was doing at the top of the generated .gemspec. Sigh.

Improvements welcome!

@lroggendorff
Copy link
Author

So, just noticed this bit here:

...if you’re running the code outside of RubyGems, you have to configure things yourself. It’s possible to manipulate the $LOAD_PATH from within the code itself, but that’s considered an anti-pattern in most cases.

Even though I pulled this technique directly from the .gemspec Bundler generated for me, I wonder if this is still not the best idea after all...

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment