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).
[ruby]
module Kernel
def desire(library)
require library
return true
rescue LoadError
STDERR.puts "warning: #{library} gem desired but not found."
return false
end
end
[/ruby]
And here’s how I optionally include the metric_fu gem.
[ruby]
desire ‘metric_fu’
[/ruby]
If a user has the gem installed, rake -T will show the tasks.
[text]
jasonn:~/sources/my_files [master] $ rake -T
(in ~/sources/my_files)
rake metrics:all
[…]
jasonn:~/sources/my_files [master] $
[/text]
If the user does not have the gem installed, rake -T will show a simple warning and continue.
[text]
jasonn:~/sources/my_files [master] $ rake -T
(in ~/sources/my_files)
warning: metric_fu gem desired but not found.
[…]
jasonn:~/sources/my_files [master] $
[/text]
I don’t remember where I first heard the desire idea, but it works pretty well.
1 Comment
>I was just reading about metric_fu this morning in Linux Journal.
Fine Jason, I'll try ruby.