How to optionally load gems

Posted by Jason Noble on 06/04/2009 in Uncategorized |

I ran into an interesting problem today at work. I wanted to optionally require a ruby gem. For example, I wanted to include the metric_fu rake tasks, but if a user doesn’t have metric_fu installed, it’s no big deal.

Here’s how I implemented it. I added a method to the Kernel space (where require lives) called desire. I desire this gem to be installed, but I should just see a warning if it’s not installed, instead of an error.

Here’s the desire method (I put this in RAILS_ROOT/Rakefile).

module Kernel
  def desire(library)
    require library
    return true
  rescue LoadError
    STDERR.puts "warning: #{library} gem desired but not found."
    return false

And here’s how I optionally include the metric_fu gem.

desire 'metric_fu'

If a user has the gem installed, rake -T will show the tasks.

jasonn:~/sources/my_files [master] $ rake -T
(in ~/sources/my_files)
rake metrics:all 
jasonn:~/sources/my_files [master] $

If the user does not have the gem installed, rake -T will show a simple warning and continue.

jasonn:~/sources/my_files [master] $ rake -T
(in ~/sources/my_files)
warning: metric_fu gem desired but not found.
jasonn:~/sources/my_files [master] $

I don’t remember where I first heard the desire idea, but it works pretty well.

1 Comment

  • Adrian says:

    >I was just reading about metric_fu this morning in Linux Journal.
    Fine Jason, I'll try ruby.

Comments are closed. Would you like to contact the author directly?

Copyright © 2008-2018 Jason Noble's Technical Adventures All rights reserved.
This site is using the Desk Mess Mirrored theme, v2.2.3, from BuyNowShop.com.