Search code examples
rubyruby-on-rails-3rubygemssidekiq

Checking if a gem is available from inside other gem


I'm currently writing a Gem for ruby, and as some of the things that I want to offer is support for either resque or sidekiq. Generally, I don't want the user to crash if the service (either one) is not available, so I'd like to load them only if the user has those gems up and running.

I've tried the following:

mymod.rb

module Mymod
  # Code code code
end

require "mymod/railtie" if defined?(Rails)
require "mymod/sidekiqworker" if defined?(Sidekiq)

mymod/sidekiqworker.rb

module mymod
  class Sidekiqworker
    include Sidekiq::Worker
    sidekiq_options :queue => :default

    def perform(path)

    end
  end
end

But when I load the gem and start the server, the class is not included (looks like sidekiq is not defined).

This works if I add a "require 'sidekiq'" at the top of the sidekiqworker file but that would defeat the purpose of allowing people to use either service.

Is there a way to see if the user has a gem installed and then allow them to use that service?

I'm using: - Ruby 1.9.3 - Rails 3 - Sidekiq 1.2.1

Any help would be greatly appreciated.


Solution

  • You normally catch the LoadError.

    begin
      require 'sidekiq'
    rescue LoadError
      # sidekiq not available
    end
    

    You can assign the result to a variable

    has_sidekiq = begin
      require 'sidekiq'
      true
    rescue LoadError
      false
    end
    
    require "mymod/sidekiqworker" if has_sidekiq