# flagbearer for Ruby

The Ruby SDK for Flagbearer. Requires Ruby 3.2 or later.

## Install

```sh
bundle add flagbearer
```

## Keys

Use a server key, which starts with `fbs_`. Server keys are secret: read them
from the environment, such as `FLAGBEARER_SERVER_KEY`, and never put them in
browser code or in the repository. Browsers use client keys, which start with
`fbc_`, through [`@flagbearer/web`](/sdks/web).

## Sync at startup

Create one client per process, when the app starts, and wait for it to sync
before accepting requests. In Rails, use an initializer:

```ruby
# config/initializers/flagbearer.rb
FLAGS = Flagbearer.init(ENV.fetch("FLAGBEARER_SERVER_KEY"))

begin
  FLAGS.sync(timeout: 10)
rescue Flagbearer::Error => e
  # Keep starting: checks use their defaults, and the SDK retries in the background.
  Rails.logger.warn("Initial Flagbearer sync failed: #{e.message}")
end

at_exit { FLAGS.close }
```

## Check per request

Pass each request's user explicitly, and a default:

```ruby
class SearchController < ApplicationController
  def index
    user = { key: current_user.id.to_s, email: current_user.email }
    @advanced = FLAGS.enabled?("advanced-search", user, default: false)
  end
end
```

The user is a Hash with `:key` and `:email`, as symbol or string keys. The key
must be a String, so convert numeric IDs with `to_s`.

The email is optional. Include it to turn flags on for testers by email.
The default is used until the client has synced, and when the flag doesn't
exist.

## Shut down

Keep the client for the life of the process, not per request. Close it on
shutdown, as the initializer above does with `at_exit`.

Short-lived jobs, like a Rake task or a serverless function, should call
`FLAGS.flush` before they exit.
