Question

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.

Was it helpful?

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

OTHER TIPS

inside your .gemspec make sure you add the required gem which your gem is dependent on as a as a runtime dependency. This way Bundler would be the one to handle the availability of that gem when your gem is installed. All you have to worry about is using the gem (i.e. require it then use it).

In your case, this would look like

# in name_of_gem.gemspec

# some code identifying your gem

s.add_runtime_dependency "rails"
s.add_runtime_dependency "sidekiq"
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top