SDKs
Ruby
Server-side decisions for Rails and Sidekiq, fork-safe, with live updates and AI config helpers.
The liftcanary gem decides on your Ruby server: Rails, Sinatra, Hanami, Sidekiq workers or scripts. One client per process refreshes the datafile in background threads, hears about published changes right away and sends events in batches. A decision takes about 5–10 µs with no network call, and it gives a user the same variation as the website, app, Node and Python SDKs.
Install#
bundle add liftcanary # or: gem install liftcanaryRuby 3.0 or newer. No dependencies: it uses only the standard library.
Usage#
LIFTCANARY = LiftCanary::Client.new(ENV.fetch("LIFTCANARY_SDK_KEY"))
LIFTCANARY.ready(timeout: 2) unless Rails.env.test? # waits for the first datafileclass ApplicationController < ActionController::Base
private
def liftcanary_user
@liftcanary_user ||= LIFTCANARY.create_user(
current_user.id,
attributes: { plan: current_user.plan, country: request.headers["CF-IPCountry"] },
anonymous_id: cookies[LiftCanary::ANONYMOUS_ID_COOKIE], # links the landing-page visit, once
page: request.original_url # for location conditions; never sent
)
end
helper_method :liftcanary_user
endclass CheckoutsController < ApplicationController
def create
flow = liftcanary_user.variable("new_checkout", "flow", "classic")
order = place_order(params, flow)
liftcanary_user.track("purchase", value: order.total, properties: { currency: order.currency })
render json: order
end
endThe client logs to Rails.logger when Rails is loaded. Views can use the helper too: liftcanary_user.enabled?("new_checkout").
The user#
| Method | Returns |
|---|---|
enabled?(flag_key) | Whether the feature is on for this user. |
variable(flag_key, name, fallback = nil) | The variable's value, or the fallback when the flag or variable is missing, null or of another kind. |
decide(flag_key, send_exposure: true) | A Decision: flag_key, enabled, variation_key, rule_key, in_experiment, reason, variables, revision. |
decide_all | Decisions for every flag, by key. |
track(event_key, value: nil, properties: nil) | Records a goal event. value must be a finite number (BigDecimal and Rational are converted). |
log_exposure(decision) | For decisions made with send_exposure: false. |
create_user(id, attributes: {}, bucketing_id: nil, page: nil, active_locations: nil, anonymous_id: nil) takes the same fields as the other SDKs. Attribute keys may be symbols or strings; values are strings, numbers, booleans or nil. Attributes are sent with events; page and active_locations never are. Decisions are thread-safe and never wait for the network. An exposure is logged only for experiment decisions, once per user, flag, rule and variation.
Signing in#
The website snippet keeps a visitor's anonymous id in the liftcanary_anon cookie (LiftCanary::ANONYMOUS_ID_COOKIE). Pass it as anonymous_id: when they sign in, as the controller above does, so results count the anonymous landing-page visit and the signed-in user as one person (see From landing page to app). The link is sent once per pair of ids in each process, so passing it on every request is free. To also keep the variation they saw before signing in, pass the same value as bucketing_id:.
Options#
Keyword arguments of LiftCanary::Client.new(sdk_key, **options).
sdk_keyrequiredString | The environment's public SDK key (pk_…). |
datafileHash | A datafile to start from (string or symbol keys, or JSON text), so the first decisions need no download. |
cdn_urlString | Where datafiles come from. Default https://cdn.liftcanary.com; use your own domain or the API when self-hosting. |
events_urlString | The collector. Default https://events.liftcanary.com. |
streamingtrue | Live updates: each published datafile arrives right away (server-sent events). false turns it off. |
stream_urlString | Where live updates connect: <stream_url>/stream/<sdk_key>. Default: cdn_url. |
polling_interval30 | Seconds between datafile checks, underneath live updates (ETag, so an unchanged datafile costs a 304). 0 turns polling off. |
event_flush_interval2 | Seconds between event sends. 0: only full batches and flush. |
event_batch_size200 | Events per request; a full batch is sent at once. |
event_max_queue_size20_000 | Events held in memory before the oldest are dropped (counted in client.events.dropped). |
model_prices{} | Price per 1M tokens per model, for AI configs: { "model" => { input: 3, output: 15 } }. |
transportNet::HTTP | Replaces the HTTP layer: call(method, url, headers, body, timeout) returns a LiftCanary::Response. Live updates then need stream_transport too. |
stream_transportNet::HTTP | The HTTP layer of live updates: call(url, headers, timeout) returns a connection with each_chunk and close. |
loggerRails.logger | Any Logger-compatible object. Without Rails, warnings go to $stderr. |
starttrue | Start the background threads now; with false, call start yourself. |
Live updates and forking servers#
- Live updates: a published change reaches every process right away, and polling goes on underneath in case the connection drops. Datafiles only ever move forward in revision.
LIFTCANARY.subscribe { … }runs (from a background thread) whenever a newer one is applied. - Forking servers (Puma with
preload_app!, Unicorn, Passenger, Sidekiq swarm): create the client once, in an initializer. Forked workers restart the background threads by themselves (aProcess._forkhook on Ruby 3.1+, the first call in the worker on 3.0) and start with an empty event queue, so nothing is sent twice. Remaining events are sent at exit; to be sure a worker flushes before it's stopped, close the client in its shutdown hook:on_worker_shutdown { LIFTCANARY.close }inconfig/puma.rb. - Jobs and scripts: events are sent every 2 seconds in the background, so call
LIFTCANARY.flush(orclose) at the end of a short-lived process. - Errors from the network or a datafile are logged with a
[liftcanary]prefix, never raised, and the last good datafile stays in use. Datafiles, decisions and variable values are frozen, so a value changed in one request can't leak into the next;dupbefore changing one.
AI configs#
Test models, prompts and parameters on real users, measured on latency, tokens, cost, errors and feedback. Your code still calls the provider.
cfg = LiftCanary.ai_config(liftcanary_user, "support_bot", model: "my-small-model", prompt: "You are a helpful assistant.")
usage = ->(r) { { input_tokens: r.usage.input_tokens, output_tokens: r.usage.output_tokens } }
reply = LiftCanary.measure_llm(liftcanary_user, cfg, usage: usage) do
llm.messages.create(model: cfg.model, system: LiftCanary.render_prompt(cfg.prompt, language: "Turkish"), **cfg.params)
end
LiftCanary.track_feedback(liftcanary_user, cfg, positive: true) # when the user rates the answercfg.params has symbol keys, ready to splat into a provider call, and costs need model_prices: on the client. measure_llm re-raises the block's error after recording it; a client that disconnects or a block left early counts as aborted. measure_llm_stream also records the time to first token, and track_llm a call you measured yourself. Prompts and answers are never sent. See AI configs and LLM experiments.