14
.
11
.
2023
16
.
01
.
2015
Ruby on Rails
Backend

Optional dependencies in gems

Karol Słuszniak
Ruby Developer

When developing textris gem, I've stumbled upon an issue with handling optional dependencies. For example, you may want to support features of other gem in yours, but only when gem user actually uses that other gem in his project. This is important, as all dependencies required by your project will be installed by bundler in user's project.

Let's look at my case from textris. I wanted to support delaying texter invocation with sidekiq, just like the one sidekiq provides out of the box for ActionMailer. Still, installing sidekiq for every project that just wants to send some SMSes without touching background jobs is not a good idea, to say the least. Note that sidekiq depends on redis server, so should I just advice every textris user to install redis in his system?

Unfortunately, there's no stock solution for this in bundler and Gem::Specification builder. So what can you do?

Rescue to the rescue

Ruby community has came up with the following pattern to solve the problem:

begin
  require 'twilio-ruby'
rescue LoadError
  # handle lack of library or just leave it be
end

Yes, this is how most (if not all) gems out there do it. Of course, there are many things that may happen in the rescue blocks.

Let's do nothing

Sometimes you don't need to do anything in rescue block. That's the case with twilio-ruby dependency of textris. The twilio-ruby gem is only used in the Twilio delivery class which will never be invoked unless user explicitly configures textris to deliver via Twilio. And if that's the case, there's no reason to avoid the undefined constant exception.

But then again, why require twilio-ruby if undefined constant error is not an issue? For example, to actually require the gem in tests and verify the collaboration of own gem with another. Another reason may be a need to require a file that is a part of another gem that doesn't get required by bundler automatically, i.e. user has something like this in her Gemfile:

gem 'some_gem', :require => false 

Requiring optional dependencies from within the main gem file may be also the only way to have an actual place in code where you state the optional dependencies, as you cannot put them into the gemspec (which really seems like a necessary addition to bundler todo list).

Let's make some noise

Many libraries choose to print a warning message in the rescue block in order to make it clear to the developer that there's something wrong. Here's an example taken from the carrierwave_securefile gem:

begin # require aes
  require 'carrierwave/securefile/aes_file.rb'
rescue LoadError
  puts "WARNING: Failed to require aes_file or openssl, AES encryption may fail!"
end

Personally I don't like the idea. I think that if dependency is important enough to bother user with errors on every application load, then it should be added as runtime dependency and just install along with gem. And if it's not required then why bother the user at all? Still, I can think of some scenarios when warnings might be useful:

  • if you support multiple alternative libraries for the same functionality (like supporting either sidekiq or resque for delayed jobs), you may have to react somehow if none of them is present in user's bundle
  • if specific version of dependent library that is present in user's bundle has some compatibility problems with your code, you may want to encourage the user to change the library version she bundles

Fallback gently

Sometimes you may want to offer some replacement functionality for your code when a specific gem is not available. That was the case with textris and sidekiq. I couldn't allow loading my sidekiq related classes when sidekiq is missing because I inherit from its classes, so there would be a constant missing error during textris gem initialization. Also, simply not loading these classes would result in lack of some textris documented constants at runtime which would be confusing to the user. You can fix this like I did by using one of ruby's sweet object reopening & mixing mechanics like the one below:

begin
  require 'sidekiq'
rescue LoadError
  require 'textris/delay/sidekiq/missing'

  Textris::Delay::Sidekiq.include(Textris::Delay::Sidekiq::Missing)
else
  require 'textris/delay/sidekiq'
  require 'textris/delay/sidekiq/proxy'
  require 'textris/delay/sidekiq/serializer'
  require 'textris/delay/sidekiq/worker'
end

What does this do? If sidekiq is present, I load all regular classes belonging to the Textris::Delay::Sidekiq module (the else block). But if there's no sidekiq in the project, I load a fallback code kept in separate file and include it in the Textris::Delay::Sidekiq module which is empty at the time because the regular classes were not loaded. This fallback code is actually very simple, it just throws an appropriate error if any of delay methods gets invoked by the user who doesn't have sidekiq in her bundle yet.

Fallback code injection allows to inform user about the missing dependency at appropriate time and in appropriate way. It also becomes handy in tests, which should describe both the "gem present" and "gem missing" scenarios. That's how you handle both scenarios:

  • gem present: as gem is added via add_development_dependency to the gemspec and main gem file requires it, you can test this scenario without further effort
  • gem missing: you can remove_const to unload dependent gem constants and invoke the code from load rescue manually to inject the fallback code for proper testing

Final note

I hope gemspec will be extended with ability to add optional dependencies, if not for any other purpose then just to present them on the gem's RubyGems page. Honestly, I have no idea on a more elegant solution for this pattern than the rescue of dependency loading, but I'm sure there is some out there waiting to be popularized. Until then, the solution described in this article should be fine.

Karol Słuszniak
Ruby Developer

Check my Twitter

Check my Linkedin

Did you like it? 

Sign up To VIsuality newsletter

READ ALSO

Visuality Poznań is here!

14
.
11
.
2023
Michał Piórkowski
Visuality
Business
HR

Why we chose Ruby on Rails and React.js for our main technologies? (FAQ).

02
.
10
.
2024
Michał Krochecki
Ruby on Rails
Backend
Frontend
Visuality

Branding: How to style your Jira?

14
.
11
.
2023
Lukasz Jackiewicz
Tutorial
Design
Project Management

How to start your UX/UI designer career

14
.
11
.
2023
Bartłomiej Bednarski
Design
Tutorial
HR

WebUSB - Bridge between USB devices and web browsers

14
.
11
.
2023
Burak Aybar
Ruby on Rails
Frontend
Backend
Tutorial

Visuality comes to town - this time it's Poznań

14
.
11
.
2023
Michał Piórkowski
Visuality
HR

How to choose a software house.

14
.
11
.
2023
Michał Piórkowski
Ruby on Rails
Business
Visuality

CSS Modules in Rails

14
.
11
.
2023
Adam Król
Ruby on Rails
Tutorial
Backend
Frontend

JSON API versus the NIH syndrome

14
.
11
.
2023
Nadia Miętkiewicz
Backend
Frontend
Tutorial

From Idea to Concept

02
.
10
.
2024
Michał Krochecki
Ruby on Rails
Business
Startups

Styling React Components

14
.
11
.
2023
Umit Naimian
Ruby on Rails
Frontend
Tutorial

How good design can help your business grow

14
.
11
.
2023
Lukasz Jackiewicz
Design
Business
Marketing

TODO not. Do, or do not.

29
.
11
.
2023
Stanisław Zawadzki
Ruby on Rails
Software

CS Lessons #003: Density map in three ways

14
.
11
.
2023
Michał Młoźniak
Ruby
Backend
Tutorial
Software

Clean code for the win

14
.
11
.
2023
Michał Piórkowski
Ruby on Rails
Backend
Frontend
Business

Crowd-operated Christmas Lights

14
.
11
.
2023
Nadia Miętkiewicz
Ruby on Rails
Backend

How to startup and be mature about it

14
.
11
.
2023
Rafał Maliszewski
Ruby on Rails
Startups
Business

A journey of a thousand miles begins with workshops

14
.
11
.
2023
Michał Piórkowski
Software
HR

CS Lessons #002: Data structures

14
.
11
.
2023
Michał Młoźniak
Ruby
Software

Summary of Phoenix workshop at Visuality

14
.
11
.
2023
Karol Słuszniak
Ruby on Rails
Visuality
Backend

CS Lessons #001: Working with binary files

14
.
11
.
2023
Michał Młoźniak
Ruby
Software

CS Lessons #000: Introduction and motivation

14
.
11
.
2023
Michał Młoźniak
Ruby
Software

Working with 40-minute intervals

14
.
11
.
2023
Sakir Temel
Software
HR

THE MATURE TECH STARTUP DILEMMA: WHAT'S NEXT

14
.
11
.
2023
Susanna Romantsova
Startups