How to optionally load gems
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
end
end
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 Comments:
I was just reading about metric_fu this morning in Linux Journal.
Fine Jason, I'll try ruby.
Post a Comment
Links to this post:
Create a Link
<< Home