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

A look back at Friendly.rb 2023

14
.
11
.
2023
Cezary Kłos
Conferences
Ruby

Debugging Rails - Ruby Junior Chronicles

14
.
11
.
2023
Piotr Witek
Ruby on Rails
Backend
Tutorial

GraphQL in Ruby on Rails: How to Extend Connections

14
.
11
.
2023
Cezary Kłos
Ruby on Rails
GraphQL
Backend
Tutorial

Tetris on Rails

17
.
03
.
2024
Paweł Strzałkowski
Ruby on Rails
Backend
Frontend
Hotwire

EURUKO 2023 - here's what you've missed

14
.
11
.
2023
Michał Łęcicki
Ruby
Conferences

Easy introduction to Connection Pool in ruby

14
.
11
.
2023
Michał Łęcicki
Ruby on Rails
Backend
Ruby
Tutorial

When crazy ideas bring great time or how we organized our first Conference!

04
.
12
.
2023
Alexander Repnikov
Ruby on Rails
Conferences
Visuality

Stacey Matrix & Takeaways - why does your IT project suck?

02
.
10
.
2024
Wiktor De Witte
Project Management
Business

A simple guide to pessimistic locking in Rails

14
.
11
.
2023
Michał Łęcicki
Ruby on Rails
Backend
Ruby
Tutorial

Poltrax design - story of POLTRAX (part 3)

04
.
12
.
2023
Mateusz Wodyk
Startups
Business
Design

Writing Chrome Extensions Is (probably) Easier Than You Think

14
.
11
.
2023
Antoni Smoliński
Tutorial
Frontend
Backend

Bounded Context - DDD in Ruby on Rails

17
.
03
.
2024
Paweł Strzałkowski
Ruby on Rails
Domain-Driven Design
Backend
Tutorial

The origin of Poltrax development - story of POLTRAX (part 2)

29
.
11
.
2023
Stanisław Zawadzki
Ruby on Rails
Startups
Business
Backend

Ruby Meetups in 2022 - Summary

14
.
11
.
2023
Michał Łęcicki
Ruby on Rails
Visuality
Conferences

Repository - DDD in Ruby on Rails

17
.
03
.
2024
Paweł Strzałkowski
Ruby on Rails
Domain-Driven Design
Backend
Tutorial

Example Application - DDD in Ruby on Rails

17
.
03
.
2024
Paweł Strzałkowski
Ruby on Rails
Domain-Driven Design
Backend
Tutorial

How to launch a successful startup - story of POLTRAX (part 1)

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

How to use different git emails for different projects

14
.
11
.
2023
Michał Łęcicki
Backend
Tutorial

Aggregate - DDD in Ruby on Rails

17
.
03
.
2024
Paweł Strzałkowski
Ruby on Rails
Domain-Driven Design
Backend
Tutorial

Visuality at wroc_love.rb 2022: It's back and it's good!

14
.
11
.
2023
Patryk Ptasiński
Ruby on Rails
Conferences
Ruby

Our journey to Event Storming

14
.
11
.
2023
Michał Łęcicki
Visuality
Event Storming

Should I use Active Record Callbacks?

14
.
11
.
2023
Mateusz Woźniczka
Ruby on Rails
Backend
Tutorial

How to rescue a transaction to roll back changes?

17
.
03
.
2024
Paweł Strzałkowski
Ruby on Rails
Backend
Ruby
Tutorial