RubyGems and Railties Can Distribute Configuration
Learn about RubyGems and Railties and how they work in Rails applications.
We'll cover the following
Distribute configuration using RubyGems and Railties
When we have more than one Rails application, there are often libraries we want to share between apps, and those libraries require a common setup. For example, we might use a message bus like RabbitMQ or Apache Kafka for asynchronous communication. We might have a library that provides simplified access to the system, along with configuration settings, such as network timeouts or error-handling behavior.
Or, we might have a convention around using, say, Bugsnag as our exception-handling service and want to have a single set of configuration settings for all apps.
A common way to manage this is to provide documentation about what to do. Or, if we’ve been inspired by the previous section, we could use code generation via a generator or template.
A better solution to this particular problem is to use Railties embedded in Ruby gems. Railties is a core component of how Rails works and is the API for customizing Rails’ initialization procedure. By putting a Railtie inside a Ruby gem, we can automatically insert configuration into any Rails app that bundles that gem.
Let’s see how it works by creating an exception-handling gem that configures and sets up Bugsnag, a common exception-handling service. Exception-handling services like Bugsnag receive reports about any exception that our app doesn’t explicitly handle. These reports can alert an on-call engineer to investigate what could be a problem with the app (Airbrake and Rollbar are two other examples).
This example will be a bit contrived because we only have one Rails app in our running example, and in the real world, we would configure Bugsnag in the one and only app we have. But, to demonstrate the point, we’ll imagine we have several Rails apps that all use Bugsnag and we want to have a common configuration.
First, let’s see what this configuration is that we want to share. Let’s suppose, in our case, we want to configure:
- The API key used with the service.
- The Rails environments in which errors are actually reported.
- The Git SHA-1 of the application in which an error occurs.
- Some common exceptions we don’t want to be reported.
Without using our to-be-implemented gem that uses Railties, the configuration would live in config/initializers/bugsnag.rb
and look like so:
Get hands-on with 1200+ tech skills courses.