fbpx

Feature flags can be used to manage which features different types of users see, conduct A/B testing, control large launches or safely rollout new features. A gem commonly used for feature flags in Ruby on Rails applications is flipper. You can quickly provide a way for application admins to control features for each release by adding a related mode. Here is how.

First add the following gems to your project:

gem “flipper”
gem “flipper-active_record”
gem “flipper-ui”

The last gem you added will create a minimal ui for the admin users to manage features in the application. Mount the ui to a route:

# config/routes.rb
YourRailsApp::Application.routes.draw do
mount Flipper::UI.app(Flipper) => ‘/manage_features’
end

Next generate and run migrations for the feature tables:

bin/rails g flipper:active_record
bin/rails db:migrate

At this point you should be able to start your rails app and navigate to localhost:3000/manage_features and see the simple ui for managing features.

Now create an additional migration for the releases.

bin/rails g migration CreateRelease

If you need to manage the features by major and minor version, add a major version and minor version column to the new table. The major version will need to be an enum in order to take advantage of Flipper’s group concept. For this example, just modify the table to add a title column. *Note, you may want to also add an identifier column as an uuid to make managing the features in the ui easier on the admins.

def change
create_table :releases do |t|
t.string :title
t.timestamps
end
end

The release record will be an actor you can use to control the features. Create a model for the release. You also might want to prevent the records from being accidentally destroyed.

class Release < ApplicationRecord validates :title, uniqueness: true validates :title, presence: true

before_destroy :raise_exception

def raise_exception
raise StandardError.new ‘Failed to destroy release’
end
end

Use the console to create a new release record.

release = Release.create(title: ‘v1’)

You can create the new feature flag using the ui or the rails console.

Flipper.add(:subscriptions)

Enable the new feature for the release (the actor)

Flipper.enable_actor(:subscriptions, release)

Check to see if the feature is enabled for the release:

Flipper.enabled?(:subscriptions, release)

Make sure the feature is not enabled globally:

Flipper.enabled?(:subscriptions)

You should now be able to apply the feature flags as needed throughout the codebase. By giving application admins the ability to control features per release you can empower them to roll back features with defects, test out new work with a small group of users, or turn features on once data migrations have been run and validated.

For other helpful Ruby on Rails tips, visit our blog. Or contact us today!