Zenmanage Ruby SDK
Feature flags for Ruby and Rails with Zenmanage. Your rules are fetched once, cached and evaluated inside your process, so checking a flag doesn't cost a network round trip.
- Boolean, string, number and JSON flags
- Targeting by context, segment and attribute
- Percentage rollouts
- Defaults for when a flag, or the API, isn't there
- Memory, filesystem or your own cache
- Rails integration: controller and view helpers, an install generator and a webhook endpoint
- No runtime dependencies
Installation
Add to your Gemfile:
gem "zenmanage"Then run bundle install, or install it directly with gem install zenmanage.
Requirements: Ruby 3.2 or later.
Documentation
- Ruby quickstart: install, Rails controllers, views, and jobs, plain Ruby and Rack, context targeting, and the webhook endpoint, step by step
- SDKs and integrations: every Zenmanage SDK and its install command
- Zenmanage documentation: API reference, targeting guides, and the rest of the developer docs
Key compatibility
This is a server-side SDK. It takes your environment's server key (it starts with srv_). Client keys (cli_) and
mobile keys (mob_) are rejected when the SDK is configured.
Quick start
require "zenmanage"
config = Zenmanage::ConfigBuilder.create
.with_environment_token(ENV["ZENMANAGE_ENVIRONMENT_TOKEN"])
.build
client = Zenmanage::Client.new(config)
if client.flags.single("new-dashboard", false).enabled?
puts "Show the new dashboard"
endCreate one client and reuse it. It holds the loaded rules.
Rails
Setup
With ZENMANAGE_ENVIRONMENT_TOKEN set, there's nothing else to do: the gem configures itself when your app boots.
To keep the settings in your app, generate an initializer:
bin/rails generate zenmanage:install# config/initializers/zenmanage.rb
Zenmanage.configure do |config|
config.environment_token = Rails.application.credentials.zenmanage_environment_token
config.cache_ttl = 300
endYou can also set single options in config/application.rb or an environment file, which applies when you don't call
Zenmanage.configure:
config.zenmanage.cache_ttl = 300Auto-configuration happens after your initializers have run. To read flags while the app is still booting, call
Zenmanage.configure first.
Settings you leave out come from the ZENMANAGE_* environment variables. The SDK logs to Rails.logger. Without a
token, your app still boots: it logs a warning and feature_enabled? returns the default.
Controllers and views
feature_enabled? and zen_flags are available in ActionController::Base and ActionController::API controllers,
and in views:
class ProductsController < ApplicationController
def show
@new_layout = feature_enabled?("new-layout")
@checkout = zen_flags.single("checkout-flow", "control").as_string
@page_size = zen_flags.single("page-size", 20).as_number
end
end<% if feature_enabled?("promo-banner") %>
<%= render "shared/promo_banner" %>
<% end %>Outside a controller (jobs, mailers, models), use Zenmanage.flags:
Zenmanage.flags
.with_context(Zenmanage::Context.single("user", user.id.to_s))
.single("new-export", false)
.enabled?Who flags are evaluated for
If a controller has a current_user, flags are evaluated for a user context with its id and, if it has one, its
name. Both are sent to Zenmanage with usage reports.
To send something else, or nothing, override the private zenmanage_context method:
class ApplicationController < ActionController::Base
private
def zenmanage_context
return unless current_user
Zenmanage::Context.new(
"user",
identifier: current_user.id.to_s, # no name sent
attributes: [Zenmanage::Attribute.new("plan", [current_user.plan])],
)
end
endReturn nil to evaluate without a context.
Sinatra and plain Rack
Without Rails, add the middleware yourself and read the flags from the Rack environment:
use Zenmanage::Rails::Middleware, client
get "/" do
env["zenmanage.flags"].single("new-home", false).enabled? ? "new" : "old"
endFlags and values
flags = client.flags
flags.single("new-feature").enabled? # boolean flags: true / false
flags.single("checkout-layout").as_string # string flags
flags.single("max-results").as_number # number flags
flags.single("theme-config").as_json # JSON flags: a Hash or an Array
flags.all.each { |flag| puts "#{flag.key}: #{flag.value}" }single reports the flag's usage; all doesn't.
Value types and coercion
Calling the "wrong" accessor never raises. Each one reads its own type and returns an empty value for the others. This is the same in every Zenmanage SDK.
| Flag type | as_bool |
as_string |
as_number |
as_json |
|---|---|---|---|---|
boolean |
the value | "" |
0 |
{} |
string |
true |
the value | 0 |
{} |
number |
true |
"" |
the value | {} |
json |
true |
"" |
0 |
the decoded value |
as_bool is true for every non-boolean flag, whatever its value. To ask whether a boolean flag is on, use
enabled?, which is false for any other type.
A JSON flag whose value is a bare scalar (5, "x") makes as_json return {}.
In Rails, as_json is also what the JSON encoder calls. To send a flag in a response, render its value or
flag.to_h, for example render json: zen_flags.all.map(&:to_h).
Contexts and targeting
A context says who you're evaluating for. Targeting rules match its type, identifier and attributes.
context = Zenmanage::Context.new("user", identifier: "user-123", name: "Jane Doe")
context.add_attribute(Zenmanage::Attribute.new("plan", ["pro"]))
context.add_attribute(Zenmanage::Attribute.new("teams", ["billing", "platform"]))
flags = client.flags.with_context(context)
flags.single("beta-feature", false).enabled?Zenmanage::Context.single("user", "user-123") is the short form, and Zenmanage::Context.from_hash builds one from a
Hash:
Zenmanage::Context.from_hash(
"type" => "organization",
"identifier" => "org-9",
"attributes" => [{ "key" => "tier", "values" => ["enterprise"] }],
)with_context returns a new manager. The one you called it on doesn't change.
Percentage rollouts
Start a rollout in Zenmanage. The SDK puts each context in or out of it by its identifier, so the same user gets the same answer every time, and raising the percentage only adds users. The bucketing matches the Zenmanage API and the other SDKs.
flags = client.flags.with_context(Zenmanage::Context.single("user", "user-42"))
flags.single("new-checkout", false).enabled?A context without an identifier isn't in any rollout.
Defaults
A default is used when a flag isn't in your rules, including when the rules couldn't be loaded.
flags.single("missing-flag", false) # boolean
flags.single("missing-flag", "control") # string
flags.single("missing-flag", 10) # number
flags.single("missing-flag", { "a" => 1 }) # JSON (an Array works too)
defaults = Zenmanage::DefaultsCollection.from_hash("new-search" => false, "page-size" => 20)
flags = client.flags.with_defaults(defaults)
flags.single("page-size").as_number
flags.all # includes defaults for keys your rules don't haveAn inline default wins over the collection. With neither, single raises Zenmanage::EvaluationError.
Keeping rules fresh
Rules are used for cache_ttl seconds (3600 by default), then reloaded by the next flag check. While one thread
reloads, the others keep using the rules they have. If a reload fails, the current rules stay in use and the SDK tries
again 30 seconds later (sooner if your TTL is shorter).
Reload now:
client.flags.refresh_rulesrefresh_rules raises Zenmanage::FetchRulesError if the rules can't be fetched, and keeps the ones it had.
Webhooks
To apply changes as soon as they're published, add a webhook for your environment in Zenmanage and mount the endpoint:
# config/routes.rb
mount Zenmanage::Webhook::Endpoint.new => "/zenmanage/webhook"Set ZENMANAGE_WEBHOOK_SECRET to the webhook's signing secret (it starts with whsec_). The endpoint checks the
X-Zenmanage-Signature header and refreshes the rules. In Sinatra or Rack:
map "/zenmanage/webhook" do
run Zenmanage::Webhook::Endpoint.new(client: client)
endA webhook reaches one process. With several (Puma workers, several hosts), the others pick the change up when their
cache_ttl passes.
To handle the request yourself, Zenmanage::Webhook.verify_signature(body, signature_header, secret) does the check.
Usage reporting
single tells Zenmanage a flag was used, with the context and the default you passed, so you can see which flags are
live and which are dead code. Reports are sent in the background and never raise.
A report that's still being sent when the process ends is lost, and single doesn't hand its report back for you to
wait on. A short script can send one more, with the same context, and wait for that one:
client.flags.report_usage("new-checkout", context)&.join. The first report can still be lost, and if both arrive
the flag counts as used twice.
Turn it off with with_usage_reporting(false) (or config.enable_usage_reporting = false). To report usage yourself,
for example after reading a flag from all:
client.flags.report_usage("new-checkout", context)Configuration
config = Zenmanage::ConfigBuilder.create
.with_environment_token("srv_your_server_key") # required
.with_cache_ttl(3600) # seconds
.with_cache_backend("memory") # "memory", "filesystem" or "null"
.with_cache_directory("/tmp/zenmanage") # required for "filesystem"
.with_usage_reporting(true)
.with_api_endpoint("https://api.zenmanage.com")
.with_logger(Logger.new($stdout))
.buildOr from environment variables, with Zenmanage::ConfigBuilder.from_environment.build:
| Variable | Setting |
|---|---|
ZENMANAGE_ENVIRONMENT_TOKEN |
server key |
ZENMANAGE_CACHE_TTL |
seconds |
ZENMANAGE_CACHE_BACKEND |
memory, filesystem, null
|
ZENMANAGE_CACHE_DIR |
filesystem cache path |
ZENMANAGE_ENABLE_USAGE_REPORTING |
true / false
|
ZENMANAGE_API_ENDPOINT |
API URL |
ZENMANAGE_WEBHOOK_SECRET |
webhook signing secret |
Caching
| Backend | What it does |
|---|---|
memory |
Default. Per process, gone on restart. |
filesystem |
Survives restarts and is shared by processes on one machine, such as Puma workers. |
null |
Nothing is cached outside the client. Set cache_ttl to 0 to fetch the rules on every check. |
To use your own store, pass anything with get(key) and set(key, value, ttl):
class RailsCache < Zenmanage::Cache::Base
def get(key) = Rails.cache.read(key)
def set(key, value, ttl = nil) = Rails.cache.write(key, value, expires_in: ttl)
end
Zenmanage.configure { |config| config.cache = RailsCache.new }Errors
Flag checks don't fail because the API is unreachable: you get your default. These are the errors you can see:
| Error | When |
|---|---|
Zenmanage::ConfigurationError |
A setting is missing or invalid, or Zenmanage.flags is called before configuring |
Zenmanage::EvaluationError |
A flag can't be found and has no default |
Zenmanage::FetchRulesError |
refresh_rules couldn't fetch the rules |
Zenmanage::InvalidRulesError |
refresh_rules got a response it can't read |
All of them subclass Zenmanage::Error.
How requests are identified
The SDK sends X-ZEN-CLIENT-AGENT: zenmanage-ruby/<version>, or zenmanage-rails/<version> when Rails is loaded.
Examples
The examples directory has runnable scripts for flags, contexts, defaults, rollouts, caching and Rails.
Development
git clone https://github.com/zenmanage/zenmanage-ruby
cd zenmanage-ruby
bundle install
bundle exec rake # tests and lint
bundle exec rspec # tests only, with a coverage report
ruby script/release_check.rb # build and check the gem without publishing
bundle exec yard doc # API docsContributing
Bug reports and pull requests are welcome. See CONTRIBUTING.md and the Code of Conduct. To report a vulnerability, see SECURITY.md.