The Featurevisor Ruby SDK evaluates flags, variations and variables in Ruby applications, from a datafile it holds in memory.
- Install
- Create an instance
- Context
- Check a flag
- Get a variation
- Get a variable
- Default values
- Evaluate everything at once
- Sticky values
- Update the datafile
- Child instances
- Events
- Diagnostics
- Evaluation details
- Modules
- Schemas
- Create a schemas instance
- Validate a value
- Read the issues
- Get a handle
- Read constraints and choices
- Read annotations
- Follow the values typed so far
- Choose the messages
- Check in code
- Options from your application
- Validate on the server
- Listen for changes
- Patterns
- Failing closed
- Fields validated alone
- Close
- OpenFeature
- CLI usage
- GitHub repositories
- Development
- License
Add the gem to your application's Gemfile:
gem 'featurevisor', '~> 4.0'Then run bundle install, or install it yourself with gem install featurevisor -v "~> 4.0". Upgrading an existing application? Follow the Ruby migration guide.
Fetch a datafile and create an instance with it:
require 'featurevisor'
require 'net/http'
require 'json'
datafile_url = 'https://cdn.example.com/featurevisor-all.json'
response = Net::HTTP.get_response(URI(datafile_url))
unless response.is_a?(Net::HTTPSuccess)
raise "Datafile request failed: HTTP #{response.code}"
end
datafile_content = JSON.parse(response.body, symbolize_names: true)
f = Featurevisor.create_featurevisor(
datafile: datafile_content
)
begin
puts f.is_enabled('checkout', { userId: 'user-4' })
ensure
f.close
endThis example closes the instance at once. In a long running application, keep it for every evaluation and close it at shutdown. Parse a datafile with symbolize_names: true, which the SDK needs, or pass the JSON string and let the SDK parse it. Every option is optional, so an instance can start without a datafile and receive one later:
| Option | Sets |
|---|---|
datafile |
The datafile to evaluate |
context |
The instance context |
sticky_features, sticky_variables |
Sticky values |
log_level, on_diagnostic |
Diagnostics |
modules |
Modules |
Create one instance and reuse it. On a server that handles many users, give each request a child instance.
On MRI, evaluations are safe from many threads, with one thread refreshing the datafile, since warm reads rely on MRI's execution model. Other Ruby implementations are not guaranteed. Apply changes, such as set_datafile, set_context, set_sticky_features, set_sticky_variables, add_module, remove_module and close, from one thread at a time, never during evaluations. Module, event and diagnostic callbacks synchronize any state of their own.
Context is a plain hash of attribute values, with symbol keys. The instance keeps a context of its own, and each evaluation can add to it.
Set it when creating the instance:
f = Featurevisor.create_featurevisor(
datafile: datafile_content,
context: {
country: 'nl'
}
)Add to it later with set_context, or replace it by passing true as the second argument:
f.set_context({
userId: 'user-4'
})
f.set_context({
userId: 'user-2',
country: 'nl'
}, true)Context passed to an evaluation is merged over the instance context for that call only:
context = {
userId: 'user-4',
country: 'nl'
}
f.is_enabled('checkout', context)get_context returns the instance context, and get_context({ country: 'de' }) shows it merged with extra values without storing them.
Dates compare as portable timestamp strings, Time or DateTime, by their instant, truncated to milliseconds. Offsets stay within 14 hours and years within 1 and 9999. A plain Date has no time or offset, so pass Time.utc(2026, 1, 1) or '2026-01-01T00:00:00Z' instead.
is_enabled reads a flag. Dutch users have the new checkout:
context = {
userId: 'user-4',
country: 'nl'
}
if f.is_enabled('checkout', context)
# show the new checkout
endget_variation returns the variation of a feature, or nil if the feature is disabled or has none:
variation = f.get_variation('pricing', context)
if variation == 'treatment'
# show the new pricing
endFor user-4 it returns 'control', and for user-2 it returns 'treatment'.
get_variable reads a feature variable with a feature key and a variable key. For user-4, the netherlands rule sets the buy button's label to 'Nu kopen':
label = f.get_variable('buyButton', 'label', context)With a context as its second argument, it reads a global variable instead. supportEmail returns 'support-nl@example.com' for user-4:
email = f.get_variable('supportEmail', context)A string second argument means a feature variable, and a hash means context for a global variable. The typed methods below follow the same rule.
Treat returned hashes and arrays as read only. The SDK can share them with its datafile rather than copy them on every evaluation, so copy a value before changing it, and never change a datafile after passing it to the instance.
Each typed method returns nil when the value has a different type, and never converts it. get_variable_integer returns nil for the string '1', and get_variable_boolean returns nil for 'true'.
get_variable_number reads a variable of type number as a Float, and also double in datafiles built before v4.
| Method | Returns |
|---|---|
get_variable_boolean |
true or false |
get_variable_string |
String |
get_variable_integer |
Integer |
get_variable_number |
Float, whole or fractional |
get_variable_array |
Array |
get_variable_object |
Hash |
get_variable_json |
Any JSON value |
settings = f.get_variable_object('checkoutSettings', context)
# { currency: 'EUR', paymentMethods: ['card'] }Read a composed global variable like any other global variable. For a string compose alias, choose the getter for the source's type, such as get_variable_string for an alias of supportEmail. It returns what the source's own getter returns, including decoded JSON and nil, with no wrapper or copy.
A composition is evaluated in this order:
- A sticky value for the whole variable, which skips everything after it.
- Root
conditions. When they miss, no source is read and no override runs. The result isdisabledValuewhen supplied, otherwisenil, with reasonconditions_unmet. - The sources, with their own sticky values, the context and modules taking part as usual.
- The overrides, which run as they do for any global variable.
Compositions have no defaultValue or useDefaultWhenDisabled. With no override match, the reason is variable_composed, and a match reports variable_override_rule, with variable_override_paths listing every override that changed the value. Only the outer hash of a composition is fresh, so treat what it holds as read only.
Pass default_variation_value or default_variable_value in the options for when an evaluation produces no value, such as a feature missing from the datafile:
label = f.get_variable(
'buyButton',
'label',
context,
{ default_variable_value: 'Buy' }
)A default counts as given whenever the key is present, so '', 0, false and nil are all valid defaults.
get_feature_evaluations evaluates every loaded feature, or only the keys you pass:
f.get_feature_evaluations(context, %w[checkout pricing buyButton])
# {
# checkout: { enabled: true },
# pricing: { enabled: true, variation: 'control' },
# buyButton: {
# enabled: true,
# variation: 'treatment',
# variables: { label: 'Nu kopen', colour: '#2563eb' }
# }
# }get_variable_evaluations does the same for global variables:
f.get_variable_evaluations(context, %w[supportEmail checkoutSettings])To see what is loaded without evaluating anything:
get_feature_keyslists every feature in the datafile, enabled or not.get_variable_keyslists global variables, andget_variable_keys('buyButton')lists that feature's variables.has_variations?('pricing')istruewhen a feature has variations, andfalsefor an unknown feature.
Both results have the shape sticky values take. A server can evaluate once per request and pass the results to the browser, so the first render matches what the server saw. The JavaScript SDK's sticky values read them there.
Sticky values take precedence over the datafile. Use them to keep a user's result fixed, to answer before a datafile has loaded, or in unit tests:
f = Featurevisor.create_featurevisor(
sticky_features: {
checkout: { enabled: true },
pricing: {
enabled: true,
variation: 'treatment'
}
},
sticky_variables: {
supportEmail: 'support@example.com'
}
)A sticky feature can also set variables. Change sticky values later with set_sticky_features and set_sticky_variables. Both merge by default, and replace the whole map when the second argument is true:
f.set_sticky_features({
checkout: { enabled: false }
}, true)Treat sticky maps as read only once given to an instance, and change them only through these methods.
set_datafile gives the instance a newer datafile, parsed with symbol keys or as a JSON string:
f.set_datafile(datafile_content)It returns true when the datafile is accepted, even if nothing changed, and false when it is rejected or the instance is closed. A rejected datafile leaves the previous one in place and is reported through diagnostics.
By default, the new datafile is merged into the current one:
- Its features, segments and global variables replace those with the same keys.
- Definitions it does not contain are kept.
- Its
revisionandschemaVersionare taken.
Pass true to replace the current datafile entirely. Do this when refreshing a complete datafile, so definitions removed from it do not linger:
f.set_datafile(datafile_content, true)Merging is what lets one instance hold datafiles for several targets, loaded as each part of the application needs them. See Loading datafiles on demand.
Fetch the datafile again every few minutes, from one thread:
refresh = Thread.new do
loop do
sleep(5 * 60)
begin
response = Net::HTTP.get_response(URI(datafile_url))
next unless response.is_a?(Net::HTTPSuccess)
f.set_datafile(JSON.parse(response.body, symbolize_names: true), true)
rescue StandardError => error
warn "Could not refresh datafile: #{error.message}"
end
end
endA failed fetch keeps the previous datafile. set_datafile does not raise for an invalid datafile, it reports it through diagnostics. Stop the thread with refresh.kill when you stop, since close does not stop your threads. Each accepted update emits datafile_set.
A server handles many users at once, so give each request a child with its own context:
child = f.spawn({
userId: 'user-4',
country: 'nl'
})
child.is_enabled('checkout')- The child copies the parent's context keys when it is spawned, and its own values win. Keys the parent adds later still reach it.
- Sticky values are not inherited. Pass
{ sticky_features: ... }as the second argument when the child needs some. - A child has the parent's evaluation methods, plus
get_context,set_context,set_sticky_features,set_sticky_variables,onandclose. closeremoves the child's listeners, including the ones it registered on its parent.
on subscribes to an event with a block and returns a lambda that unsubscribes.
Emitted for every accepted datafile:
unsubscribe = f.on('datafile_set') do |event|
revision = event[:revision]
previous_revision = event[:previousRevision]
revision_changed = event[:revisionChanged]
replaced = event[:replaced]
features = event[:features]
variables = event[:variables]
segments = event[:segments]
# evaluate the listed features and variables again
end
unsubscribe.callreplaced says whether the datafile replaced the previous one or merged into it. features and variables list the keys whose results may have changed: those added, updated or removed, and those that depend on them through conditions, segments and composition sources, however indirectly. Evaluate those again and you have everything that changed.
segments lists the segments whose definitions were added, changed or, on a replace, removed. If a new datafile has the netherlands segment take Belgium too, segments is [:netherlands], and features and variables include checkout and supportEmail, whose conditions read it. The first datafile lists every feature, global variable and segment. sections lists the changed entries of each datafile section, such as schemas.
Emitted by set_context:
f.on('context_set') do |event|
context = event[:context] # the new instance context
keys = event[:keys] # the top level keys whose values changed
endkeys compares values, so a key set again to the value it already holds is not listed. Starting from the instance context { userId: 'user-4', country: 'nl' }:
f.set_context(
country: 'de'
)
# keys: [:country]
f.set_context(
country: 'de',
plan: 'paid'
)
# keys: [:plan]
f.set_context(
{
userId: 'user-4',
country: 'de'
},
true
)
# keys: [:plan]A replace also lists the keys it removed, as plan above. Hashes and arrays compare item by item, and numbers by value, so 30 and 30.0 are the same, but a hash or array given again as the same object counts as changed, since it may have been changed in place.
Emitted by set_sticky_features, with features, every feature that had a sticky value before the call or has one after it, and replaced:
f.on('sticky_features_set') { |event| puts event[:features] }Emitted by set_sticky_variables, with variables and replaced:
f.on('sticky_variables_set') { |event| puts event[:variables] }Emitted for every diagnostic at error:
f.on('error') { |event| warn event[:diagnostic][:message] }The SDK reports what happens during evaluation as diagnostics, at one of five levels: fatal, error, warn, info and debug. By default, those at info and above go to the console with a [Featurevisor] prefix.
debug shows how each value was evaluated, which helps when a result surprises you. Set the level when creating the instance, or later:
f = Featurevisor.create_featurevisor(log_level: 'debug')
f.set_log_level('warn')To send diagnostics somewhere other than the console, pass a handler:
f = Featurevisor.create_featurevisor(
on_diagnostic: ->(diagnostic) {
# send diagnostic[:level], [:code], [:message] and [:details] to your observability system
}
)Every diagnostic has :level, :code, :message and a :details hash. Values about an evaluation, such as featureKey, variableKey, reason and evaluation, are in :details. :module, :moduleName and :originalError say where an error came from, when known. A handler that raises stops neither other handlers nor evaluations.
conditions_parse_error is an error diagnostic for malformed stringified conditions. It fires once per selector per datafile load, on first read for v4 datafiles and during set_datafile for v3 datafiles. Its :details contain conditions with the raw string, entityType and entityKey.
The whole malformed selector evaluates to false, even under not, while other entities keep working and set_datafile returns true for an otherwise valid datafile. A malformed root gate is unmet and reports conditions_unmet.
Dependency cycles, and chains of more than 256 dependencies, fail the whole evaluation with reason error. SDK evaluation errors return the ordinary false or nil result, and other entities keep working.
The evaluate methods return how a value was reached, not only the value:
f.evaluate_flag('checkout', context)
f.evaluate_variation('pricing', context)
f.evaluate_variable('buyButton', 'label', context)
f.evaluate_variable('supportEmail', context)For user-4, evaluate_flag returns:
{
type: 'flag',
feature_key: 'checkout',
reason: 'rule',
bucket_key: 'user-4.checkout',
bucket_value: 89312,
rule_key: 'netherlands',
enabled: true
}Every evaluation has a :type and a :reason. Others appear when they apply:
:feature_key, absent for global variables, so check for it before using it:bucket_keyand:bucket_value, from 0 to 100,000, and the:rule_keythat matched:enabled,:variationand:variation_value:variable_key,:variable_value,:variable_schemaand:variable, the global variable's definition:variable_override_keyand:variable_override_indexwhen a keyed override matched, and:variable_override_pathfor a nested one:variable_override_paths, every override path matched in order, for accumulating overrides. The singular fields describe the last match:conditionswhen a root gate stopped the evaluation:errorwhen evaluation failed
Test specs can assert them.
| Reason | Meaning |
|---|---|
feature_not_found |
The feature is not in the datafile |
disabled |
The feature is disabled |
no_variations |
A variation was requested from a feature without variations |
variation_disabled |
A disabled feature returned its disabledVariationValue |
variable_not_found |
The feature variable or global variable is not in the datafile |
variable_default |
The variable returned its default value |
variable_composed |
A global variable read its composition sources with no override match |
variable_disabled |
A disabled feature returned the variable's disabled value |
variable_override_variation |
A feature variable override matched inside a variation |
variable_override_rule |
A feature variable override or global variable override matched |
conditions_unmet |
Root conditions did not match. See :conditions |
no_match |
No rule, allocation or variation matched, or the bucket fell outside the rollout |
forced |
A force entry supplied the result |
sticky |
A sticky value supplied the result |
rule |
A matching rule supplied the result |
allocated |
Bucketing allocated the result |
error |
Evaluation failed. See :error |
A module hooks into evaluation. It can change the context before an evaluation, change the result after it, or decide how users are bucketed. Every part is optional:
audit_module = {
name: 'audit',
setup: ->(api) {
api[:on_diagnostic].call(->(diagnostic) {
# diagnostics at this module's own level
})
api[:report_diagnostic].call({
level: 'info',
code: 'module_ready',
message: "Ready for revision #{api[:get_revision].call}"
})
},
before_evaluation: ->(options) {
# :type, :feature_key, :variable_key and :context
options.merge(context: options[:context].merge(plan: 'paid'))
},
after_evaluation: ->(evaluation, options) {
# log evaluation[:error] when evaluation[:reason] is 'error'
evaluation
},
bucket_key: ->(options) { options[:bucket_key] },
# between 0 and 100,000
bucket_value: ->(options) { options[:bucket_value] },
close: -> {
# clean up when the instance closes
}
}before_evaluation and after_evaluation run for flags, variations and both kinds of variable, every module in registration order, and must return the options and the evaluation, changed or not. A variable evaluation without a :feature_key is a global one.
before_evaluation also runs when a schema validates, with type schema and the schema's key instead of a :feature_key, so context it adds reaches the schema's conditions too. after_evaluation does not run then, since a validation's result is not an evaluation. Check type before reading the keys.
The before evaluation and after evaluation phases each use the module membership at the start of that phase, and the bucket key and bucket value phases each use their own. Adding or removing a module during a phase does not change the iteration already in progress.
If setup raises, the module is not registered. The SDK removes the diagnostic subscriptions it made, reports module_setup_error, and calls its close if it has one.
Conditions and composition members are evaluated through modules too. Their options include :dependency_of, naming the requesting evaluation by type, feature_key and variable_key. :dependency_purpose is 'condition' for an eligibility check and 'composition' for a consumed member value. Direct calls have neither.
When tracking consumed evaluations, skip eligibility checks, not every read with :dependency_of, since a variation read through a composition can be an experiment exposure. Within one call, repeated reads with the same inputs and purpose are memoized, so callbacks can run fewer times than there are reads. Return the same result for the same input during one evaluation, and pass values that change through the context.
Pass modules when creating the instance, or add them later:
f = Featurevisor.create_featurevisor(
modules: [audit_module]
)
remove = f.add_module(tracking_module)
# later
remove.call
f.remove_module('audit')A package, such as schemas, reads the datafile through the API setup receives:
api[:get_entry].call(section, key)returns an entry of a section, a top level key besides Featurevisor's own whose value is an object, such asschemas, with symbol keys. Treat it as read only.api[:get_entry_keys]lists a section's keys.api[:match_conditions]answers the package's own conditions with the instance's engine, segments and feature leaves included. Itsreadersanswer leaves only the package knows, such asinput, returningFeaturevisor::Conditions.missing_valuefor no value.api[:evaluate].call({ type:, key:, context: }) { |scope| ... }evaluates the package's own entry as a getter evaluates a flag. Every module'sbefore_evaluationruns first, withtypeandkeynaming the entry, and the conditions the block answers withscope.match_conditions(conditions, readers)read the context the modules leave, in one dependency session. The block's result is returned.
Feature and variable leaves reach modules as dependencies, with :dependency_of naming the package's entry. A module with no evaluation callbacks, such as a package's, costs evaluations nothing.
Schemas validate data against the schemas your datafiles deliver, with the instance you already have, and the same rules, messages and conditions as @featurevisor/schemas in JavaScript.
Schemas are experimental, so their API may change in a minor release, as in JavaScript.
They are a separate gem, released with the same version as the SDK:
gem 'featurevisor-schemas', '~> 4.1'Create it from the SDK instance. Call it s, as the SDK instance is f:
require 'featurevisor-schemas'
s = Featurevisor::Schemas.create(f)It holds no copy of the schemas. Every call reads the datafile f has now, so a new datafile applies at the next validation. Compiled schemas are kept until a datafile changes them, and handles are safe to share between threads.
value = {
email: 'user-1@example.com',
displayName: 'A',
country: 'nl'
}
result = s.validate('signUp', value)
unless result.valid?
# show result.issues beside the form's fields
ends.validate(key, value)returns a result with the value itself and itsissues. It never coerces, fills defaults or strips keys.s.valid?(key, value)returns a boolean.s.parse(key, value)returns the value, or raisesFeaturevisor::Schemas::ValidationError, for a controller or a script that wants a value or a stop.- All three take
context:, merged over the instance's, for the conditions a schema's rules read. - A validation runs as the schema's own evaluation, so a module's
before_evaluationsees it, withtypeschemaand the schema'skey, and context the module adds reaches every condition, as it does for flags. s.keyslists the schemas the datafile has, ands.key?(key)says whether it has one.
A value can be hashes with string or symbol keys, arrays and primitives, or a Struct.
A key the datafile does not have fails closed, with one schemaNotFound issue, and a schema_not_found diagnostic at warn, once per key and datafile. A field the schema lacks reports its schemaNotFound issue alone, since the schema is there. s.get keeps no handle for a key the datafile lacks.
Every issue has a message, a path of object keys and array indices, the code of the rule that failed, its params, and the schema validated. issue.field gives its path as a form names a field, such as items.0.name.
Validation reports every issue it finds, so a form can mark every field at once. An issue about a field with a title carries it in params[:title], and one whose rule a mutation set names it in mutation.
| Code | Raised when |
|---|---|
type |
The value has another type |
const, enum |
The value is not one allowed |
minimum, maximum |
A number is out of range |
minLength, maxLength |
A string is too short or too long |
pattern, format |
A string has the wrong shape |
minItems, maxItems |
An array has too few or too many items |
uniqueItems |
An array repeats an item |
required, additionalProperties |
A key is missing, or there is one it does not allow |
oneOf |
No branch matches, or more than one does |
refine |
An issues entry matches, or a check in code fails |
refineError |
A check in code raises, or the schema itself cannot be applied |
schemaNotFound |
The datafile has no such schema or field |
result.flatten groups the messages by field, in the shape of Zod's flattenError, and so does flatten on a ValidationError, for an error response.
A handle is one schema as an object your code holds: it validates, and describes the schema's fields, constraints, choices and annotations for a form. s.get(key) gives one:
sign_up = s.get('signUp')A handle is stable, and reads the current datafile whenever it is used, so keep one for the life of the application.
| Member | What it is |
|---|---|
validate, valid?, parse |
As on s, without the key |
field(path) |
The handle of one field, such as field('displayName') |
fields |
An object's fields' handles, in order, each with its name |
constraints, field_constraints |
HTML validation attributes, and field_constraints by field path on an object, below |
options, field_options, option(value) |
Its choices, field_options by field path on an object, and one choice by value |
render_as |
What its rules say the field renders as, such as 'select' |
annotations |
Its annotations |
with_input(input) |
The same handle with an input |
reads |
The fields its rules' conditions read |
subscribe { } |
A call when a new datafile changes the schema |
key, path, name |
The schema's key, and the field's path and own name |
field takes a field name as form libraries write it: address.city, items.0.name or items[0].name, and items[].name for every item alike. It follows references and stops at oneOf. A path the schema lacks fails closed with schemaNotFound.
constraints are named after HTML attributes:
sign_up.field('displayName').constraints
# required: true, min_length: 2, max_length: 40
sign_up.field('displayName').constraints.attributes
# { required: true, minlength: 2, maxlength: 40 }, for a viewrequired, when the key is required, so an input left empty fails. A keyrequiredlists counts, whether or notpropertiesholds it, so an object withadditionalPropertiesonly, or none at all, still reports each missing key asrequiredmin_lengthandmax_length, from the same rules on a stringminandmax, fromminimumandmaximumon a numberstepof 1, for anintegermultiple, for an array, such as a multiple select
options lists a field's choices in the order of its rules, each with what its annotations say, and option(value) finds one, for showing a value saved earlier:
country = sign_up.field('country')
country.options # nl, de and be, each with its fields
country.option('nl').title # 'Netherlands'
country.option('fr') # nilA schema the datafile lacks has no constraints and no choices, so a form renders before its datafile arrives. render_as answers the switch every generic form writes, from the field's rules alone: 'text', 'date-time', 'version', 'number', 'boolean', 'select', 'multiselect', 'object' or 'list'. Your own annotation, such as input: select, still wins over it.
A handle's annotations are its node's own, and fields gives an object's fields in its order:
sign_up.annotations['title'] # 'Create your account'
sign_up.fields.map(&:path)
# ['displayName', 'email', 'country']default is the value a form starts a field with, and a handle from with_input has the one a mutation sets. Fields an order annotation leaves out come after it, in name order by Unicode code point, as in every SDK. A field or schema the datafile lacks has no annotations, {}. Annotations on Schemas writes them.
A handle's constraints and choices describe the schema's own rules, which no condition changes. with_input(input) gives the same handle with an input, such as a form's values, with the mutations that match it applied, so a tax ID shows as required once a business account is chosen:
values = {
accountType: 'business',
country: 'nl'
}
sign_up.field('taxId').constraints.required # false
sign_up.with_input(values).field('taxId').constraints.required # trueEvery member follows the input, at every depth. reads lists the fields the conditions of a handle's mutations and issues read, so a form can validate again only when one of them changes.
messages: on create words every schema's issues, per code, as a template or a lambda of the params:
s = Featurevisor::Schemas.create(
f,
messages: {
required: 'This field is required',
maxLength: ->(params, info) { "#{params[:length]} of #{params[:maxLength]} characters" }
}
)messages: on s.get words one form, by field and code, such as { displayName: { maxLength: 'Names fit {maxLength} characters' } }. For each issue, the first of these that words it wins:
- A check in code's own message, then the form's.
- The schema's own, and then the
messageof its issues entry. - The application's, from
messages:oncreate. - The default, in English.
translate: on create gets each issue, with the message chosen, and returns what the issue says, or nil to keep it. With translations, messages: holds keys, such as errors.required, and translate: turns each into text:
s = Featurevisor::Schemas.create(
f,
translate: ->(issue, info) { I18n.t(issue.message, **issue.params, default: nil) }
)Some checks need your application, such as whether a display name is taken. Give them to a handle in refine:, each a Refinement with a key and a check, and the path it checks, a message and reads as it needs them:
sign_up = s.get('signUp', refine: [
Featurevisor::Schemas::Refinement.new(
key: 'nameAvailable',
path: 'displayName',
check: ->(display_name, info) { !User.exists?(display_name: display_name) },
message: 'That display name is taken'
)
])
result = sign_up.validate(value)checkgets the value at its path, andinfowith the wholeinputand thecontext, whereinfo.read('country')reads another field. It returnstruewhen the value passes.- It runs after the schema's rules, and only when nothing at or inside its path has an issue already, so a name that is too short never reaches your database.
- Without a
path, the check gets the whole value, and runs only when the value has no issue at all.readsnames other fields whose issues hold it back too, such asitemsfor a check of an order's total. - Its issue has code
refineandparams[:refine]'nameAvailable', with the field's title. A check that raises givesrefineError, and validation fails closed. - Checks run in order, synchronously.
Some lists only your application can answer for, such as cities for a city field. Give a handle an OptionSource in option_sources:, with a key, a path, and a search, a lookup or both:
cities = Featurevisor::Schemas::OptionSource.new(
key: 'cities',
path: 'city',
reads: ['country'],
search: ->(query, info) { City.where(country: info.read('country')).search(query).map(&:name) },
lookup: ->(city, info) { City.find_by(country: info.read('country'), name: city)&.then { |found| { title: found.name } } },
message: 'Choose a city from the list'
)
sign_up = s.get('signUp', option_sources: [cities])
city = sign_up.with_input({ country: 'nl' }).field('city')
city.search('am')
# Amsterdam and Amersfoortsearchreturns choices shaped likeoptions, or values alone. A handle'ssearchpasses it the values given towith_input, so the cities follow the country.searchable?says whether a field has one.lookupreturns the choice for a value,truewhen it carries nothing more, ornilwhen there is none. A handle'slookup(value)returns the schema's own choice first, then the source's.- Validation runs
lookupas a check in code, after the schema's rules, only for a value that is there, and not while a fieldreadsnames has an issue. A value it cannot find has codeenum, worded bymessage.
parse answers a request with a value or a ValidationError, whose flatten gives the issues by field:
class SignUpsController < ApplicationController
def create
value = Featurevisor.schemas.parse('signUp', params.to_unsafe_h)
render json: create_account(value)
rescue Featurevisor::Schemas::ValidationError => error
render json: error.flatten, status: :bad_request
end
endFeaturevisor.schemas stands for wherever your application keeps s. A rule changed in your project reaches the browser and the server at their next datafile, so the two never disagree.
subscribe calls its block when a new datafile changes the schema, through a schema it references too, and returns a lambda that stops it:
stop = s.get('signUp').field('country').subscribe { render_choices }A datafile whose schema is unchanged calls nothing. s.close stops every listener the instance started and removes its module from the Featurevisor instance.
Schema patterns are JavaScript regular expressions with the u flag, and they mean the same here: ^ and $ are the start and end of the value, \s is JavaScript's whitespace, and . reads an emoji as one character, as lengths do. A pattern that does not compile with u, such as [a-z\_], fails every value, as does a type the package does not know, which reports a type issue.
A schema that fails values closed says why with an error diagnostic, once per datafile revision, so a new datafile reports again:
schema_pattern_unsupported, for a pattern that does not compile.schema_mutation_error, withrefineError, for a mutation whose operations cannot be applied.schema_reference_depth, withrefineError. Validation follows at most 128 references inside one another, which limits how deep a value can nest through them: a tree whose nodes each reference the tree's schema can be 128 levels deep, and the node at the 129th fails closed. The message readsSchema "tree" fails the value closed, since the value is nested more than 128 references deep.schema_check_error, withrefineError, for a check in code or an option source'slookupthat raises. ItsdetailsholdschemaKey,check, the check's key, andpath, the check's path as written or an empty string, and the diagnostic carries theoriginalError. It is reported once per schema and check.
A field's handle validates the field's value, so a check's info.input in a handle from field is the field's value, and only checks that read no other field run there. A handle from the schema's root with with_input, such as with_input(values).field('city'), gives the whole input. Ruby has no way to give a field handle no value, since nil is JSON null, which is a value, so a field validated with nil is checked as null and not read as absent.
The message translator, translate:, runs last, once mutations have named the issues whose rules they set or changed, so it sees issue.mutation.
close removes event listeners and closes modules, on the instance and on a child. Closing twice does nothing more:
f.closeRuby collects unreachable cycles, but an instance your application still references stays alive, so close instances and children when you are done with them.
The OpenFeature provider is published as a separate gem. This keeps OpenFeature code and dependencies out of applications that only use the Featurevisor SDK.
The provider currently requires Ruby 3.4 or newer because that is the minimum version supported by the official OpenFeature Ruby SDK.
Install the provider:
gem "featurevisor-openfeature", "~> 4.0"It installs the matching featurevisor gem and the official openfeature-sdk ~> 0.6.5 dependency. The provider requires Ruby 3.4 or later, while the separate base gem supports Ruby 3.0 or later without OpenFeature. The provider and base SDK deliberately share the same version, and the provider requires that exact Featurevisor version.
require "featurevisor/openfeature_provider"
provider = Featurevisor::OpenFeatureProvider.new(
datafile: datafile_content,
)
OpenFeature::SDK.configure do |config|
config.set_provider_and_wait(provider)
end
client = OpenFeature::SDK.build_client
enabled = client.fetch_boolean_value(
flag_key: "checkout",
default_value: false,
evaluation_context: OpenFeature::SDK::EvaluationContext.new(targeting_key: "user-4"),
)Use checkout for a flag, checkout:variation for its variation, buyButton:label for its label variable, and variable:supportEmail for a global variable. Boolean variables use the boolean resolver. Arrays, hashes, and JSON variables use the object resolver.
OpenFeature's targeting key maps to userId by default. targeting_key_field, key_separator, variation_key, and global_variable_prefix can customize the mapping. The global variable prefix defaults to variable and cannot contain the separator.
Pass Featurevisor initialization options to the provider to configure the instance it owns:
provider = Featurevisor::OpenFeatureProvider.new(
datafile: datafile_content,
targeting_key_field: "accountId",
key_separator: "/",
variation_key: "$variation",
)Reuse an existing Featurevisor instance:
f = Featurevisor.create_featurevisor(datafile: datafile_content)
provider = Featurevisor::OpenFeatureProvider.new(featurevisor: f)The caller owns an instance passed this way. Provider shutdown does not close it. Call f.close when every consumer is finished with it. When the provider creates the instance from options, the provider owns and closes it. If both are supplied, featurevisor takes precedence over the options hash.
An invalid initial datafile in an owned instance fails set_provider_and_wait with a provider initialization error carrying PARSE_ERROR, independently of log_level. A valid datafile update clears the error and emits readiness. Shutdown removes provider subscriptions and closes only an owned instance.
Root conditions_unmet outcomes map to OpenFeature DISABLED. Composed values and matched overrides map to TARGETING_MATCH. The provider does not decode composed JSON values again.
See the OpenFeature provider guide for resolution reasons, errors, metadata, tracking, lifecycle, and providers for other languages.
After adding the gem to your Gemfile as shown in Install, install it with:
bundle installUse bundle exec featurevisor for a bundled installation, featurevisor for a global gem installation, or bin/featurevisor from this SDK repository.
The native test runner requires Node.js 24 or later. Install the Node.js CLI in your Featurevisor project:
npm install --save-dev @featurevisor/cli@^4.0.0The native CLI provides test, benchmark and assess-distribution. Use the Node.js CLI for authoring commands such as init, lint and build. Native commands delegate project parsing, test listing, matrix expansion and datafile generation to npx featurevisor, then evaluate with this Ruby SDK. The SDK runtime has no Node.js dependency.
Options use kebab case, such as --project-directory-path. The camelCase forms from earlier releases still work, and --root-directory-path is an alias for --project-directory-path. Pass values as --name=value or --name value. Repeat --target to select several targets in order. Run <command> --help to list every option.
Duplicate targets are evaluated once, at their first position. --n and -n accept a positive integer.
Segment owners and checks run through ordinary SDK gates, including feature and variable dependencies, fixed at, context, sticky state and child state. Selected Target segment specializations remain authoritative. Compiled execution definitions restore only missing segments. Attribute only chains may run without an environment. Dependent segments require their selected datafile. Transitive references are preflighted before getters run. Synthetic gates are excluded from coverage. Testing does not automatically run lint.
bundle exec featurevisor test \
--project-directory-path=/path/to/featurevisor-project \
--only-failuresSee Testing for authoring specs and Checks for check syntax and operators.
Useful test options:
--key-pattern=<pattern>and--assertion-pattern=<pattern>filter tests.--entity-type=scenarioselects scenarios, and--entity-type=schemaschema specs, which validate their values with thefeaturevisor-schemasgem as the JavaScript CLI does. Without that gem, each schema spec case fails asking for it.--set=<set>selects one project set. Omitting--setruns all sets.--case=<id>reruns one expanded case. Copy the opaque ID or rerun command from a failure report.--json --prettyproduces an indented JSON report.--coveragereports observed rule and override selections.--uncoveredlists features and global variables without associated specs.--only-failures,--quiet,--verboseand--show-datafilecontrol diagnostic output.
Printed rerun commands use POSIX shell quoting. JSON reports also include raw argument arrays.
Contributor instructions are in the repository development guide.
The examples below use a project without environments. Add --environment=<name> if your project configures environments. In a sets project, omit --set to run every set or pass --set=<name>. Repeat --target=<key> to evaluate specific target datafiles. The Node.js CLI validates these options and builds the datafiles. Ruby evaluates them. Replace checkout with a feature defined in your project.
bundle exec featurevisor benchmark \
--project-directory-path=/path/to/featurevisor-project \
--feature=checkout \
--context='{"country":"nl"}' \
--n=1000Use --variation for a variation or --variable=<key> for a feature variable. Omit --feature to benchmark a global variable. Do not combine --variation with --variable. See Benchmarking.
bundle exec featurevisor assess-distribution \
--project-directory-path=/path/to/featurevisor-project \
--feature=checkout \
--populate-uuid=userId \
--n=1000Repeat --populate-uuid=<key> to generate UUID values for multiple context attributes. Supply one key per option. See Assess distribution.
- SDK: featurevisor/featurevisor-ruby
- Example application: featurevisor/featurevisor-example-ruby
The aggregate evaluation reference has moved to Evaluate everything at once.
The sticky state reference has moved to Sticky values.
After checking out the repository, run make install to install dependencies.
$ bundle exec rspec
$ make test-base
$ make test-example-1Run bundle exec rspec spec/readme_initialization_spec.rb to execute the actual initialization snippet with simulated HTTP responses and transport errors. This check also runs in the ordinary SDK suite and CI.
Build and verify both gems with:
$ make buildThe build produces featurevisor-VERSION.gem, featurevisor-schemas-VERSION.gem and featurevisor-openfeature-VERSION.gem. The artifact verifier confirms that OpenFeature code and dependencies are absent from the base gem and present only in the provider gem.
The next release is 4.1.0 for all three gems. Keep both Gemfile lockfiles aligned with the shared version. Run make test, make test-base and make build before tagging. The artefact check verifies the provider's exact dependency on the base gem and their separate contents.
- Update the shared version in
lib/featurevisor/version.rb - Run
bundle install - Push commit to
mainbranch - Wait for CI to complete
- Tag the release with the same version number, for example
vX.Y.Z - The workflow verifies that the tag matches the shared version
- The workflow publishes
featurevisorfirst, followed byfeaturevisor-openfeature
The gems are separate RubyGems packages built from the same repository. Publishing the base gem first ensures the provider's exact Featurevisor dependency is available when the provider is published. If the second push fails, rerun or retry the provider publication without republishing the existing base version.
MIT © Fahad Heylaal