Tagged With   gem:name=local_gem , post:lang=ruby , post:type=tutorial

Local Gem Loads Your Current Code

The other day while actively developing a gem, I got tired of rake reinstalling it to test its effect in irb with some other gems. I wanted to use the edge version of my gem, version now.

So I hacked up $LOAD_PATH:

  $LOAD_PATH.unshift '/my/path/to/gem/lib'

This effectively made my live gem directory a gem, as far as requiring files is concerned. However once I did this in irb a couple of times and even in a file, it started to feel dirty and repetitious. Why couldn’t I just require my local gem just like I do when it’s installed in my gem directories? So I hacked on it later and out came LocalGem.

LocalGem simply maps names to file paths and when given a name, adds its corresponding path to $LOAD_PATH like above. You can setup the name-path mapping via a yaml config file or a method call.

  require 'local_gem'
  LocalGem.setup_config do |c|
    c.gems = {'mygem'=>'/path/to/mygem', 'anothergem'=>'/path/to/anothergem'}

LocalGem then provides two methods, local_gem() and local_require() to act like gem() and require() but with knowledge of your local gems. You can use these two methods in one of three ways, depending on how much you want LocalGem to invade your namespace:

Peace time:

  LocalGem.local_gem 'mygem'
  LocalGem.local_require 'anothergem'

Diplomacy is fading:

  include LocalGem
  local_gem 'mygem'
  local_require 'anothergem'

You’re fscked:

  require 'local_gem/override'
  gem 'mygem'
  require 'anothergem'

Give it a whirl with:

 sudo gem install local_gem

Since LocalGem effectively lets you make any subset of Ruby code gem-like, some other cool uses for it could be:

  • To gemify all those cloned Github projects that aren’t gems. You may want to look at coral if you’re doing this enough.
  • Wrap up a subsection of a gem as a local gem
  • Wrap up any group of unloved Ruby files in the same directory as a local gem

Feel free to check the purty docs and github page as well.

Enjoyed this post? Tell others! hacker newsHacker News | twitterTwitter | DeliciousDelicious | redditReddit
blog comments powered by Disqus