featurevisor 3.1.0 → 4.1.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
data/README.md CHANGED
@@ -1,48 +1,56 @@
1
1
  # Featurevisor Ruby SDK <!-- omit in toc -->
2
2
 
3
- This is a port of Featurevisor [JavaScript SDK](https://featurevisor.com/docs/sdks/javascript/) v3.x to Ruby, providing a way to evaluate feature flags, variations, and variables in your Ruby applications.
4
-
5
- This SDK is compatible with Featurevisor v3 projects and v2 datafiles.
3
+ The Featurevisor Ruby SDK evaluates flags, variations and variables in Ruby applications, from a datafile it holds in memory.
6
4
 
7
5
  ## Table of contents <!-- omit in toc -->
8
6
 
9
- - [Installation](#installation)
10
- - [Public API](#public-api)
11
- - [Initialization](#initialization)
12
- - [Evaluation types](#evaluation-types)
7
+ - [Install](#install)
8
+ - [Create an instance](#create-an-instance)
9
+ - [Concurrency](#concurrency)
13
10
  - [Context](#context)
14
- - [Setting initial context](#setting-initial-context)
15
- - [Setting after initialization](#setting-after-initialization)
16
- - [Replacing existing context](#replacing-existing-context)
17
- - [Manually passing context](#manually-passing-context)
18
- - [Check if enabled](#check-if-enabled)
19
- - [Getting variation](#getting-variation)
20
- - [Getting variables](#getting-variables)
21
- - [Type specific methods](#type-specific-methods)
22
- - [Getting global variables](#getting-global-variables)
23
- - [Getting aggregate evaluations](#getting-aggregate-evaluations)
24
- - [Sticky features and variables](#sticky-features-and-variables)
25
- - [Initialize with sticky](#initialize-with-sticky)
26
- - [Set sticky afterwards](#set-sticky-afterwards)
27
- - [Setting datafile](#setting-datafile)
28
- - [Merging by default](#merging-by-default)
29
- - [Replacing](#replacing)
30
- - [Loading datafiles on demand](#loading-datafiles-on-demand)
31
- - [Updating datafile](#updating-datafile)
32
- - [Interval-based update](#interval-based-update)
33
- - [Evaluation details](#evaluation-details)
34
- - [Diagnostics](#diagnostics)
35
- - [Levels](#levels)
36
- - [Handler](#handler)
11
+ - [Check a flag](#check-a-flag)
12
+ - [Get a variation](#get-a-variation)
13
+ - [Get a variable](#get-a-variable)
14
+ - [Typed methods](#typed-methods)
15
+ - [Composed variables](#composed-variables)
16
+ - [Default values](#default-values)
17
+ - [Evaluate everything at once](#evaluate-everything-at-once)
18
+ - [Hand results from server to client](#hand-results-from-server-to-client)
19
+ - [Sticky values](#sticky-values)
20
+ - [Update the datafile](#update-the-datafile)
21
+ - [Merge or replace](#merge-or-replace)
22
+ - [Refresh on an interval](#refresh-on-an-interval)
23
+ - [Child instances](#child-instances)
37
24
  - [Events](#events)
38
25
  - [`datafile_set`](#datafile_set)
39
26
  - [`context_set`](#context_set)
40
- - [`sticky_features_set` and `sticky_variables_set`](#sticky_features_set-and-sticky_variables_set)
27
+ - [`sticky_features_set`](#sticky_features_set)
28
+ - [`sticky_variables_set`](#sticky_variables_set)
41
29
  - [`error`](#error)
30
+ - [Diagnostics](#diagnostics)
31
+ - [Evaluation errors](#evaluation-errors)
32
+ - [Evaluation details](#evaluation-details)
33
+ - [Evaluation reasons](#evaluation-reasons)
42
34
  - [Modules](#modules)
43
- - [Defining a module](#defining-a-module)
44
- - [Registering modules](#registering-modules)
45
- - [Child instance](#child-instance)
35
+ - [Dependency evaluations](#dependency-evaluations)
36
+ - [Register a module](#register-a-module)
37
+ - [Read the datafile from a module](#read-the-datafile-from-a-module)
38
+ - [Schemas](#schemas)
39
+ - [Create a schemas instance](#create-a-schemas-instance)
40
+ - [Validate a value](#validate-a-value)
41
+ - [Read the issues](#read-the-issues)
42
+ - [Get a handle](#get-a-handle)
43
+ - [Read constraints and choices](#read-constraints-and-choices)
44
+ - [Read annotations](#read-annotations)
45
+ - [Follow the values typed so far](#follow-the-values-typed-so-far)
46
+ - [Choose the messages](#choose-the-messages)
47
+ - [Check in code](#check-in-code)
48
+ - [Options from your application](#options-from-your-application)
49
+ - [Validate on the server](#validate-on-the-server)
50
+ - [Listen for changes](#listen-for-changes)
51
+ - [Patterns](#patterns)
52
+ - [Failing closed](#failing-closed)
53
+ - [Fields validated alone](#fields-validated-alone)
46
54
  - [Close](#close)
47
55
  - [OpenFeature](#openfeature)
48
56
  - [CLI usage](#cli-usage)
@@ -50,6 +58,7 @@ This SDK is compatible with Featurevisor v3 projects and v2 datafiles.
50
58
  - [Test against local monorepo's example-1](#test-against-local-monorepos-example-1)
51
59
  - [Benchmark](#benchmark)
52
60
  - [Assess distribution](#assess-distribution)
61
+ - [GitHub repositories](#github-repositories)
53
62
  - [Development](#development)
54
63
  - [Setting up](#setting-up)
55
64
  - [Running tests](#running-tests)
@@ -58,805 +67,880 @@ This SDK is compatible with Featurevisor v3 projects and v2 datafiles.
58
67
 
59
68
  <!-- FEATUREVISOR_DOCS_BEGIN -->
60
69
 
61
- ## Installation
62
-
63
- Add this line to your application's Gemfile:
64
-
65
- ```ruby
66
- gem 'featurevisor'
67
- ```
68
-
69
- And then execute:
70
-
71
- ```bash
72
- $ bundle install
73
- ```
74
-
75
- Or install it yourself as:
76
-
77
- ```bash
78
- $ gem install featurevisor
79
- ```
70
+ ## Install
80
71
 
81
- ## Public API
82
-
83
- The main runtime API is `Featurevisor.create_featurevisor`:
72
+ Add the gem to your application's Gemfile:
84
73
 
85
74
  ```ruby
86
- f = Featurevisor.create_featurevisor(
87
- datafile: datafile_content
88
- )
75
+ gem 'featurevisor', '~> 4.0'
89
76
  ```
90
77
 
91
- Most applications only need this factory and the returned `Featurevisor::Instance`. Public extension and observability APIs include modules, diagnostics, events, and the datafile structures accepted by the factory.
92
-
93
- Concurrent evaluations are safe after an instance is configured. Do not mutate or close the same instance concurrently with evaluations. Serialize calls to `set_datafile`, `set_context`, `set_sticky_features`, `set_sticky_variables`, `add_module`, `remove_module`, and `close`. Module, event, and diagnostic callbacks must synchronize mutable state that they capture.
78
+ Then run `bundle install`, or install it yourself with `gem install featurevisor -v "~> 4.0"`. Upgrading an existing application? Follow the [Ruby migration guide](https://featurevisor.com/docs/migrations/v4/ruby/).
94
79
 
95
- ## Initialization
80
+ ## Create an instance
96
81
 
97
- The SDK can be initialized by passing [datafile](https://featurevisor.com/docs/building-datafiles/) content directly:
82
+ Fetch a [datafile](https://featurevisor.com/docs/building-datafiles/) and create an instance with it:
98
83
 
99
84
  ```ruby
100
85
  require 'featurevisor'
101
86
  require 'net/http'
102
87
  require 'json'
103
88
 
104
- # Fetch datafile from URL
105
- datafile_url = 'https://cdn.yoursite.com/datafile.json'
89
+ datafile_url = 'https://cdn.example.com/featurevisor-all.json'
106
90
  response = Net::HTTP.get_response(URI(datafile_url))
91
+ unless response.is_a?(Net::HTTPSuccess)
92
+ raise "Datafile request failed: HTTP #{response.code}"
93
+ end
107
94
 
108
- # Parse JSON with symbolized keys (required)
109
95
  datafile_content = JSON.parse(response.body, symbolize_names: true)
110
96
 
111
- # Create SDK instance
112
97
  f = Featurevisor.create_featurevisor(
113
98
  datafile: datafile_content
114
99
  )
100
+ begin
101
+ puts f.is_enabled('checkout', { userId: 'user-4' })
102
+ ensure
103
+ f.close
104
+ end
115
105
  ```
116
106
 
117
- **Important**: When parsing JSON datafiles, you must use `symbolize_names: true` to ensure proper key handling by the SDK.
118
-
119
- Alternatively, you can pass a JSON string directly and the SDK will parse it automatically:
107
+ This 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](#update-the-datafile):
120
108
 
121
- ```ruby
122
- # Option 1: Parse JSON yourself (recommended)
123
- datafile_content = JSON.parse(json_string, symbolize_names: true)
124
- f = Featurevisor.create_featurevisor(datafile: datafile_content)
109
+ | Option | Sets |
110
+ | ------------------------------------- | -------------------------------- |
111
+ | `datafile` | The datafile to evaluate |
112
+ | `context` | The [instance context](#context) |
113
+ | `sticky_features`, `sticky_variables` | [Sticky values](#sticky-values) |
114
+ | `log_level`, `on_diagnostic` | [Diagnostics](#diagnostics) |
115
+ | `modules` | [Modules](#modules) |
125
116
 
126
- # Option 2: Pass JSON string directly (automatic parsing)
127
- f = Featurevisor.create_featurevisor(datafile: json_string)
128
- ```
117
+ Create one instance and reuse it. On a server that handles many users, give each request a [child instance](#child-instances).
129
118
 
130
- ## Evaluation types
119
+ ### Concurrency
131
120
 
132
- We can evaluate 3 types of values against a particular [feature](https://featurevisor.com/docs/features/):
133
-
134
- - [**Flag**](#check-if-enabled) (`boolean`): whether the feature is enabled or not
135
- - [**Variation**](#getting-variation) (`string`): the variation of the feature (if any)
136
- - [**Variables**](#getting-variables): variable values of the feature (if any)
137
-
138
- These evaluations are run against the provided context.
121
+ 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.
139
122
 
140
123
  ## Context
141
124
 
142
- Contexts are [attribute](https://featurevisor.com/docs/attributes/) values that we pass to SDK for evaluating [features](https://featurevisor.com/docs/features/) against.
143
-
144
- Think of the conditions that you define in your [segments](https://featurevisor.com/docs/segments/), which are used in your feature's [rules](https://featurevisor.com/docs/features/#rules).
125
+ Context is a plain hash of [attribute](https://featurevisor.com/docs/attributes/) values, with symbol keys. The instance keeps a context of its own, and each evaluation can add to it.
145
126
 
146
- They are plain hashes:
127
+ Set it when creating the instance:
147
128
 
148
129
  ```ruby
149
- context = {
150
- userId: '123',
151
- country: 'nl',
152
- # ...other attributes
153
- }
154
- ```
155
-
156
- Context can be passed to SDK instance in various different ways, depending on your needs:
157
-
158
- ### Setting initial context
159
-
160
- You can set context at the time of initialization:
161
-
162
- ```ruby
163
- require 'featurevisor'
164
-
165
130
  f = Featurevisor.create_featurevisor(
131
+ datafile: datafile_content,
166
132
  context: {
167
- deviceId: '123',
168
133
  country: 'nl'
169
134
  }
170
135
  )
171
136
  ```
172
137
 
173
- This is useful for values that don't change too frequently and available at the time of application startup.
174
-
175
- ### Setting after initialization
176
-
177
- You can also set more context after the SDK has been initialized:
138
+ Add to it later with `set_context`, or replace it by passing `true` as the second argument:
178
139
 
179
140
  ```ruby
180
141
  f.set_context({
181
- userId: '234'
142
+ userId: 'user-4'
182
143
  })
183
- ```
184
-
185
- This will merge the new context with the existing one (if already set).
186
144
 
187
- ### Replacing existing context
188
-
189
- If you wish to fully replace the existing context, you can pass `true` in second argument:
190
-
191
- ```ruby
192
145
  f.set_context({
193
- deviceId: '123',
194
- userId: '234',
195
- country: 'nl',
196
- browser: 'chrome'
197
- }, true) # replace existing context
146
+ userId: 'user-2',
147
+ country: 'nl'
148
+ }, true)
198
149
  ```
199
150
 
200
- ### Manually passing context
201
-
202
- You can optionally pass additional context manually for each and every evaluation separately, without needing to set it to the SDK instance affecting all evaluations:
151
+ Context passed to an evaluation is merged over the instance context for that call only:
203
152
 
204
153
  ```ruby
205
154
  context = {
206
- userId: '123',
155
+ userId: 'user-4',
207
156
  country: 'nl'
208
157
  }
209
158
 
210
- is_enabled = f.is_enabled('my_feature', context)
211
- variation = f.get_variation('my_feature', context)
212
- variable_value = f.get_variable('my_feature', 'my_variable', context)
159
+ f.is_enabled('checkout', context)
213
160
  ```
214
161
 
215
- When manually passing context, it will merge with existing context set to the SDK instance before evaluating the specific value.
162
+ `get_context` returns the instance context, and `get_context({ country: 'de' })` shows it merged with extra values without storing them.
216
163
 
217
- Further details for each evaluation types are described below.
164
+ 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.
218
165
 
219
- ## Check if enabled
166
+ ## Check a flag
220
167
 
221
- Once the SDK is initialized, you can check if a feature is enabled or not:
168
+ `is_enabled` reads a [flag](https://featurevisor.com/docs/flags/). Dutch users have the new `checkout`:
222
169
 
223
170
  ```ruby
224
- feature_key = 'my_feature'
225
-
226
- is_enabled = f.is_enabled(feature_key)
171
+ context = {
172
+ userId: 'user-4',
173
+ country: 'nl'
174
+ }
227
175
 
228
- if is_enabled
229
- # do something
176
+ if f.is_enabled('checkout', context)
177
+ # show the new checkout
230
178
  end
231
179
  ```
232
180
 
233
- You can also pass additional context per evaluation:
181
+ ## Get a variation
182
+
183
+ `get_variation` returns the [variation](https://featurevisor.com/docs/variations/) of a feature, or `nil` if the feature is disabled or has none:
234
184
 
235
185
  ```ruby
236
- is_enabled = f.is_enabled(feature_key, {
237
- # ...additional context
238
- })
239
- ```
186
+ variation = f.get_variation('pricing', context)
240
187
 
241
- ## Getting variation
188
+ if variation == 'treatment'
189
+ # show the new pricing
190
+ end
191
+ ```
242
192
 
243
- If your feature has any [variations](https://featurevisor.com/docs/features/#variations) defined, you can evaluate them as follows:
193
+ For `user-4` it returns `'control'`, and for `user-2` it returns `'treatment'`.
244
194
 
245
- ```ruby
246
- feature_key = 'my_feature'
195
+ ## Get a variable
247
196
 
248
- variation = f.get_variation(feature_key)
197
+ `get_variable` reads a [feature variable](https://featurevisor.com/docs/variables/#feature-variables) with a feature key and a variable key. For `user-4`, the `netherlands` rule sets the buy button's label to `'Nu kopen'`:
249
198
 
250
- if variation == 'treatment'
251
- # do something for treatment variation
252
- else
253
- # handle default/control variation
254
- end
199
+ ```ruby
200
+ label = f.get_variable('buyButton', 'label', context)
255
201
  ```
256
202
 
257
- Additional context per evaluation can also be passed:
203
+ With a context as its second argument, it reads a [global variable](https://featurevisor.com/docs/variables/#global-variables) instead. `supportEmail` returns `'support-nl@example.com'` for `user-4`:
258
204
 
259
205
  ```ruby
260
- variation = f.get_variation(feature_key, {
261
- # ...additional context
262
- })
206
+ email = f.get_variable('supportEmail', context)
263
207
  ```
264
208
 
265
- ## Getting variables
209
+ 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.
266
210
 
267
- Your features may also include [variables](https://featurevisor.com/docs/features/#variables), which can be evaluated as follows:
211
+ 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.
268
212
 
269
- ```ruby
270
- variable_key = 'bgColor'
213
+ ### Typed methods
271
214
 
272
- bg_color_value = f.get_variable('my_feature', variable_key)
273
- ```
215
+ 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'`.
216
+
217
+ `get_variable_number` reads a variable of [type `number`](https://featurevisor.com/docs/variables/#number) as a `Float`, and also `double` in datafiles built before v4.
274
218
 
275
- Additional context per evaluation can also be passed:
219
+ | Method | Returns |
220
+ | ---------------------- | ---------------------------- |
221
+ | `get_variable_boolean` | `true` or `false` |
222
+ | `get_variable_string` | `String` |
223
+ | `get_variable_integer` | `Integer` |
224
+ | `get_variable_number` | `Float`, whole or fractional |
225
+ | `get_variable_array` | `Array` |
226
+ | `get_variable_object` | `Hash` |
227
+ | `get_variable_json` | Any JSON value |
276
228
 
277
229
  ```ruby
278
- bg_color_value = f.get_variable('my_feature', variable_key, {
279
- # ...additional context
280
- })
230
+ settings = f.get_variable_object('checkoutSettings', context)
231
+ # { currency: 'EUR', paymentMethods: ['card'] }
281
232
  ```
282
233
 
283
- ### Type specific methods
234
+ ### Composed variables
284
235
 
285
- Next to generic `get_variable()` methods, there are also type specific methods available for convenience:
236
+ Read a [composed global variable](https://featurevisor.com/docs/variables/#compose-values) 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.
286
237
 
287
- ```ruby
288
- f.get_variable_boolean(feature_key, variable_key, context = {})
289
- f.get_variable_string(feature_key, variable_key, context = {})
290
- f.get_variable_integer(feature_key, variable_key, context = {})
291
- f.get_variable_double(feature_key, variable_key, context = {})
292
- f.get_variable_array(feature_key, variable_key, context = {})
293
- f.get_variable_object(feature_key, variable_key, context = {})
294
- f.get_variable_json(feature_key, variable_key, context = {})
295
- ```
238
+ A composition is evaluated in this order:
239
+
240
+ 1. A sticky value for the whole variable, which skips everything after it.
241
+ 2. Root `conditions`. When they miss, no source is read and no override runs. The result is `disabledValue` when supplied, otherwise `nil`, with reason `conditions_unmet`.
242
+ 3. The sources, with their own sticky values, the context and modules taking part as usual.
243
+ 4. The [overrides](https://featurevisor.com/docs/variables/#override-composed-values), which run as they do for any global variable.
296
244
 
297
- Type specific methods do not coerce values. `get_variable_integer` returns `nil` for the string `"1"`, and boolean getters return `nil` for non-boolean values.
245
+ 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.
298
246
 
299
- ## Getting global variables
247
+ ## Default values
300
248
 
301
- Global variables use the same methods with a single variable key:
249
+ 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:
302
250
 
303
251
  ```ruby
304
- message = f.get_variable_string('welcomeMessage', context)
305
- value = f.get_variable('checkoutSettings', context)
306
- evaluation = f.evaluate_variable('checkoutSettings', context)
252
+ label = f.get_variable(
253
+ 'buyButton',
254
+ 'label',
255
+ context,
256
+ { default_variable_value: 'Buy' }
257
+ )
307
258
  ```
308
259
 
309
- Global variables resolve sticky values first, then required features, then the first matching override, and finally their default value.
260
+ A default counts as given whenever the key is present, so `''`, `0`, `false` and `nil` are all valid defaults.
310
261
 
311
- ## Getting aggregate evaluations
262
+ ## Evaluate everything at once
312
263
 
313
- You can get evaluations of all features available in the SDK instance:
264
+ `get_feature_evaluations` evaluates every loaded feature, or only the keys you pass:
314
265
 
315
266
  ```ruby
316
- all_evaluations = f.get_feature_evaluations({})
317
-
318
- puts all_evaluations
267
+ f.get_feature_evaluations(context, %w[checkout pricing buyButton])
319
268
  # {
320
- # myFeature: {
269
+ # checkout: { enabled: true },
270
+ # pricing: { enabled: true, variation: 'control' },
271
+ # buyButton: {
321
272
  # enabled: true,
322
- # variation: "control",
323
- # variables: {
324
- # myVariableKey: "myVariableValue",
325
- # },
326
- # },
327
- #
328
- # anotherFeature: {
329
- # enabled: true,
330
- # variation: "treatment",
273
+ # variation: 'treatment',
274
+ # variables: { label: 'Nu kopen', colour: '#2563eb' }
331
275
  # }
332
276
  # }
333
277
  ```
334
278
 
335
- This is handy especially when you want to pass all evaluations from a backend application to the frontend.
336
-
337
- Global variable values are available separately:
279
+ `get_variable_evaluations` does the same for global variables:
338
280
 
339
281
  ```ruby
340
- global_variables = f.get_variable_evaluations({})
282
+ f.get_variable_evaluations(context, %w[supportEmail checkoutSettings])
341
283
  ```
342
284
 
343
- ## Sticky features and variables
285
+ To see what is loaded without evaluating anything:
344
286
 
345
- For the lifecycle of the SDK instance in your application, you can set some features with sticky values, meaning that they will not be evaluated against the fetched [datafile](https://featurevisor.com/docs/building-datafiles/):
287
+ - `get_feature_keys` lists every feature in the datafile, enabled or not.
288
+ - `get_variable_keys` lists global variables, and `get_variable_keys('buyButton')` lists that feature's variables.
289
+ - `has_variations?('pricing')` is `true` when a feature has variations, and `false` for an unknown feature.
346
290
 
347
- Sticky values belong to an SDK or child instance. Feature and global variable sticky values are independent.
291
+ ### Hand results from server to client
348
292
 
349
- ### Initialize with sticky
293
+ Both results have the shape [sticky values](#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](https://featurevisor.com/docs/sdks/javascript/#hand-results-from-server-to-client) read them there.
350
294
 
351
- ```ruby
352
- require 'featurevisor'
295
+ ## Sticky values
296
+
297
+ 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:
353
298
 
299
+ ```ruby
354
300
  f = Featurevisor.create_featurevisor(
355
301
  sticky_features: {
356
- myFeatureKey: {
302
+ checkout: { enabled: true },
303
+ pricing: {
357
304
  enabled: true,
358
- # optional
359
- variation: 'treatment',
360
- variables: {
361
- myVariableKey: 'myVariableValue'
362
- }
363
- },
364
- anotherFeatureKey: {
365
- enabled: false
305
+ variation: 'treatment'
366
306
  }
367
307
  },
368
308
  sticky_variables: {
369
- welcomeMessage: 'Welcome back'
309
+ supportEmail: 'support@example.com'
370
310
  }
371
311
  )
372
312
  ```
373
313
 
374
- Once initialized with sticky features, the SDK will look for values there first before evaluating the targeting conditions and going through the bucketing process.
375
-
376
- ### Set sticky afterwards
377
-
378
- You can also set sticky features after the SDK is initialized:
314
+ 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`:
379
315
 
380
316
  ```ruby
381
317
  f.set_sticky_features({
382
- myFeatureKey: {
383
- enabled: true,
384
- variation: 'treatment',
385
- variables: {
386
- myVariableKey: 'myVariableValue'
387
- }
388
- },
389
- anotherFeatureKey: {
390
- enabled: false
391
- }
392
- }, true) # replace existing sticky features (false by default)
393
-
394
- f.set_sticky_variables({ welcomeMessage: 'Welcome back' }, true)
318
+ checkout: { enabled: false }
319
+ }, true)
395
320
  ```
396
321
 
397
- ## Setting datafile
322
+ Treat sticky maps as read only once given to an instance, and change them only through these methods.
323
+
324
+ ## Update the datafile
398
325
 
399
- You may also initialize the SDK without passing `datafile`, and set it later on:
326
+ `set_datafile` gives the instance a newer datafile, parsed with symbol keys or as a JSON string:
400
327
 
401
328
  ```ruby
402
- # Parse with symbolized keys before setting
403
- datafile_content = JSON.parse(json_string, symbolize_names: true)
404
329
  f.set_datafile(datafile_content)
405
-
406
- # Or pass JSON string directly for automatic parsing
407
- f.set_datafile(json_string)
408
330
  ```
409
331
 
410
- **Important**: When calling `set_datafile()`, ensure JSON is parsed with `symbolize_names: true` if you're parsing it yourself.
411
-
412
- ### Merging by default
413
-
414
- By default, `set_datafile(datafile)` merges the incoming datafile into the SDK's current datafile:
332
+ 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](#diagnostics).
415
333
 
416
- - top-level metadata such as `schemaVersion`, `revision`, and `featurevisorVersion` comes from the incoming datafile
417
- - `segments` are merged, with incoming entries overriding existing ones
418
- - `features` are merged, with incoming entries overriding existing ones
334
+ ### Merge or replace
419
335
 
420
- This means you can call `set_datafile` more than once with different datafiles, and the SDK instance accumulates their features, segments, and global variables together.
336
+ By default, the new datafile is merged into the current one:
421
337
 
422
- ### Replacing
338
+ - Its features, segments and global variables replace those with the same keys.
339
+ - Definitions it does not contain are kept.
340
+ - Its `revision` and `schemaVersion` are taken.
423
341
 
424
- To fully replace the stored datafile, pass `true` as the second argument:
342
+ Pass `true` to replace the current datafile entirely. Do this when refreshing a complete datafile, so definitions removed from it do not linger:
425
343
 
426
344
  ```ruby
427
345
  f.set_datafile(datafile_content, true)
428
346
  ```
429
347
 
430
- ### Loading datafiles on demand
431
-
432
- Because merging is the default, a single SDK instance can start with a small datafile and load more datafiles later as your application needs them, instead of downloading every feature upfront.
433
-
434
- This pairs well with [targets](https://featurevisor.com/docs/targets/), where each target produces a smaller datafile for a specific part of your application:
435
-
436
- ```ruby
437
- require "open-uri"
438
-
439
- f = Featurevisor.create_featurevisor({})
440
-
441
- def load_datafile(f, target)
442
- url = "https://cdn.yoursite.com/production/featurevisor-#{target}.json"
443
- datafile = JSON.parse(URI.open(url).read, symbolize_names: true)
444
-
445
- # merges into whatever was loaded before
446
- f.set_datafile(datafile)
447
- end
448
-
449
- load_datafile(f, "products")
450
-
451
- # later, when the user reaches checkout
452
- load_datafile(f, "checkout")
453
- ```
454
-
455
- ### Updating datafile
456
-
457
- You can set the datafile as many times as you want in your application, which will result in emitting a [`datafile_set`](#datafile-set) event that you can listen and react to accordingly.
458
-
459
- The triggers for setting the datafile again can be:
460
-
461
- - periodic updates based on an interval (like every 5 minutes), or
462
- - reacting to:
463
- - a specific event in your application (like a user action), or
464
- - an event served via websocket or server-sent events (SSE)
348
+ Merging is what lets one instance hold datafiles for several [targets](https://featurevisor.com/docs/targets/), loaded as each part of the application needs them. See [Loading datafiles on demand](https://featurevisor.com/docs/use-cases/on-demand-datafiles/).
465
349
 
466
- ### Interval-based update
350
+ ### Refresh on an interval
467
351
 
468
- Here's an example of using interval-based update:
352
+ Fetch the datafile again every few minutes, from one thread:
469
353
 
470
354
  ```ruby
471
- require 'net/http'
472
- require 'json'
473
-
474
- def update_datafile(f, datafile_url)
355
+ refresh = Thread.new do
475
356
  loop do
476
- sleep(5 * 60) # 5 minutes
477
-
357
+ sleep(5 * 60)
478
358
  begin
479
359
  response = Net::HTTP.get_response(URI(datafile_url))
480
- datafile_content = JSON.parse(response.body)
481
- f.set_datafile(datafile_content)
482
- rescue => e
483
- # handle error
484
- puts "Failed to update datafile: #{e.message}"
360
+ next unless response.is_a?(Net::HTTPSuccess)
361
+
362
+ f.set_datafile(JSON.parse(response.body, symbolize_names: true), true)
363
+ rescue StandardError => error
364
+ warn "Could not refresh datafile: #{error.message}"
485
365
  end
486
366
  end
487
367
  end
488
-
489
- # Start the update thread
490
- Thread.new { update_datafile(f, datafile_url) }
491
368
  ```
492
369
 
493
- ## Diagnostics
494
-
495
- By default, Featurevisor reports diagnostics to the console for `info` level and above with a `[Featurevisor]` prefix.
496
-
497
- ### Levels
370
+ A 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`](#datafile-set).
498
371
 
499
- Available diagnostic levels are `fatal`, `error`, `warn`, `info`, and `debug`.
372
+ ## Child instances
500
373
 
501
- Set the level during initialization or update it afterwards:
374
+ A server handles many users at once, so give each request a child with its own context:
502
375
 
503
376
  ```ruby
504
- f = Featurevisor.create_featurevisor(log_level: "debug")
505
- f.set_log_level("info")
506
- ```
507
-
508
- ### Handler
509
-
510
- Use `on_diagnostic` to send structured diagnostics to your observability system:
377
+ child = f.spawn({
378
+ userId: 'user-4',
379
+ country: 'nl'
380
+ })
511
381
 
512
- ```ruby
513
- f = Featurevisor.create_featurevisor(
514
- log_level: "info",
515
- on_diagnostic: ->(diagnostic) {
516
- puts "#{diagnostic[:level]} #{diagnostic[:code]} #{diagnostic[:message]}"
517
- }
518
- )
382
+ child.is_enabled('checkout')
519
383
  ```
520
384
 
521
- Every diagnostic has `:level`, `:code`, `:message`, and an object-shaped `:details` hash. Optional `:module`, `:moduleName`, and `:originalError` fields describe provenance. Evaluation metadata belongs in `:details`.
522
-
523
- Diagnostic handlers are isolated from SDK behaviour. An exception in a handler does not stop other handlers or evaluations.
524
-
385
+ - 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.
386
+ - Sticky values are not inherited. Pass `{ sticky_features: ... }` as the second argument when the child needs some.
387
+ - A child has the parent's evaluation methods, plus `get_context`, `set_context`, `set_sticky_features`, `set_sticky_variables`, `on` and `close`.
388
+ - `close` removes the child's listeners, including the ones it registered on its parent.
525
389
 
526
390
  ## Events
527
391
 
528
- Featurevisor SDK implements a simple event emitter that allows you to listen to events that happen in the runtime.
529
-
530
- You can listen to these events that can occur at various stages in your application:
392
+ `on` subscribes to an event with a block and returns a lambda that unsubscribes.
531
393
 
532
394
  ### `datafile_set`
533
395
 
396
+ Emitted for every accepted datafile:
397
+
534
398
  ```ruby
535
399
  unsubscribe = f.on('datafile_set') do |event|
536
- revision = event[:revision] # new revision
400
+ revision = event[:revision]
537
401
  previous_revision = event[:previousRevision]
538
- revision_changed = event[:revisionChanged] # true if revision has changed
539
-
540
- # list of feature keys that have new updates,
541
- # and you should re-evaluate them
402
+ revision_changed = event[:revisionChanged]
403
+ replaced = event[:replaced]
542
404
  features = event[:features]
405
+ variables = event[:variables]
406
+ segments = event[:segments]
543
407
 
544
- # handle here
408
+ # evaluate the listed features and variables again
545
409
  end
546
410
 
547
- # stop listening to the event
548
411
  unsubscribe.call
549
412
  ```
550
413
 
551
- The `features` array will contain keys of features that have either been:
414
+ `replaced` 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.
552
415
 
553
- - added, or
554
- - updated, or
555
- - removed
416
+ `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](#read-the-datafile-from-a-module), such as `schemas`.
556
417
 
557
- compared to the previous datafile content that existed in the SDK instance.
418
+ ### `context_set`
558
419
 
559
- The event also includes `replaced`, which is `true` when the datafile replaced the previous content instead of merging into it.
420
+ Emitted by `set_context`:
560
421
 
561
- ### `context_set`
422
+ ```ruby
423
+ f.on('context_set') do |event|
424
+ context = event[:context] # the new instance context
425
+ keys = event[:keys] # the top level keys whose values changed
426
+ end
427
+ ```
428
+
429
+ `keys` 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' }`:
562
430
 
563
431
  ```ruby
564
- unsubscribe = f.on('context_set') do |event|
565
- replaced = event[:replaced] # true if context was replaced
566
- context = event[:context] # the new context
432
+ f.set_context(
433
+ country: 'de'
434
+ )
435
+ # keys: [:country]
567
436
 
568
- puts 'Context set'
569
- end
437
+ f.set_context(
438
+ country: 'de',
439
+ plan: 'paid'
440
+ )
441
+ # keys: [:plan]
442
+
443
+ f.set_context(
444
+ {
445
+ userId: 'user-4',
446
+ country: 'de'
447
+ },
448
+ true
449
+ )
450
+ # keys: [:plan]
570
451
  ```
571
452
 
572
- ### `sticky_features_set` and `sticky_variables_set`
453
+ 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.
454
+
455
+ ### `sticky_features_set`
456
+
457
+ Emitted by `set_sticky_features`, with `features`, every feature that had a sticky value before the call or has one after it, and `replaced`:
573
458
 
574
459
  ```ruby
575
- feature_unsubscribe = f.on('sticky_features_set') do |event|
576
- replaced = event[:replaced] # true if sticky features got replaced
577
- features = event[:features] # list of all affected feature keys
460
+ f.on('sticky_features_set') { |event| puts event[:features] }
461
+ ```
578
462
 
579
- puts 'Sticky features set'
580
- end
463
+ ### `sticky_variables_set`
581
464
 
582
- variable_unsubscribe = f.on('sticky_variables_set') do |event|
583
- variables = event[:variables]
584
- end
465
+ Emitted by `set_sticky_variables`, with `variables` and `replaced`:
466
+
467
+ ```ruby
468
+ f.on('sticky_variables_set') { |event| puts event[:variables] }
585
469
  ```
586
470
 
587
471
  ### `error`
588
472
 
589
- ```ruby
590
- unsubscribe = f.on('error') do |event|
591
- diagnostic = event[:diagnostic]
592
- code = diagnostic[:code]
593
- message = diagnostic[:message]
473
+ Emitted for every diagnostic at `error`:
594
474
 
595
- puts "Featurevisor error: #{code} #{message}"
596
- end
475
+ ```ruby
476
+ f.on('error') { |event| warn event[:diagnostic][:message] }
597
477
  ```
598
478
 
599
- The `error` event is emitted for diagnostics reported with `level: "error"`.
479
+ ## Diagnostics
600
480
 
601
- ## Evaluation details
481
+ 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.
602
482
 
603
- Besides logging with debug level enabled, you can also get more details about how the feature variations and variables are evaluated in the runtime against given context:
483
+ `debug` shows how each value was evaluated, which helps when a result surprises you. Set the level when creating the instance, or later:
604
484
 
605
485
  ```ruby
606
- # flag
607
- evaluation = f.evaluate_flag(feature_key, context = {})
486
+ f = Featurevisor.create_featurevisor(log_level: 'debug')
608
487
 
609
- # variation
610
- evaluation = f.evaluate_variation(feature_key, context = {})
488
+ f.set_log_level('warn')
489
+ ```
611
490
 
612
- # variable
613
- evaluation = f.evaluate_variable(feature_key, variable_key, context = {})
491
+ To send diagnostics somewhere other than the console, pass a handler:
614
492
 
615
- # global variable
616
- global_evaluation = f.evaluate_variable(variable_key, context = {})
493
+ ```ruby
494
+ f = Featurevisor.create_featurevisor(
495
+ on_diagnostic: ->(diagnostic) {
496
+ # send diagnostic[:level], [:code], [:message] and [:details] to your observability system
497
+ }
498
+ )
617
499
  ```
618
500
 
619
- The returned object will always contain the following properties:
501
+ 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.
620
502
 
621
- - `feature_key`: the feature key when evaluating a feature
622
- - `reason`: the reason how the value was evaluated
503
+ ### Evaluation errors
623
504
 
624
- And optionally these properties depending on whether you are evaluating a feature variation or a variable:
505
+ `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`.
625
506
 
626
- - `bucket_value`: the bucket value between 0 and 100,000
627
- - `rule_key`: the rule key
628
- - `error`: the error object
629
- - `enabled`: if feature itself is enabled or not
630
- - `variation`: the variation object
631
- - `variation_value`: the variation value
632
- - `variable_key`: the variable key
633
- - `variable_value`: the variable value
634
- - `variable_schema`: the variable schema
507
+ 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`.
635
508
 
636
- ## Modules
509
+ 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.
637
510
 
638
- Modules allow you to intercept the evaluation process and customize SDK behaviour.
511
+ ## Evaluation details
639
512
 
640
- For feature evaluations, all `before` callbacks run in registration order, followed by all `before_evaluation` callbacks. After evaluation and caller defaults, all `after_evaluation` callbacks run, followed by all `after` callbacks. Global variable evaluations use only `before_evaluation` and `after_evaluation`. Required feature checks run through the complete module pipeline, and transformed defaults are preserved.
513
+ The `evaluate` methods return how a value was reached, not only the value:
641
514
 
642
- `before` and `after` remain available as deprecated feature-only compatibility callbacks. Use `before_evaluation` and `after_evaluation` for new modules so the same callbacks can handle feature and global variable evaluations.
515
+ ```ruby
516
+ f.evaluate_flag('checkout', context)
517
+ f.evaluate_variation('pricing', context)
518
+ f.evaluate_variable('buyButton', 'label', context)
519
+ f.evaluate_variable('supportEmail', context)
520
+ ```
643
521
 
644
- ### Defining a module
522
+ For `user-4`, `evaluate_flag` returns:
645
523
 
646
- A module is a simple hash with a unique recommended `name` and optional lifecycle functions:
524
+ ```ruby
525
+ {
526
+ type: 'flag',
527
+ feature_key: 'checkout',
528
+ reason: 'rule',
529
+ bucket_key: 'user-4.checkout',
530
+ bucket_value: 89312,
531
+ rule_key: 'netherlands',
532
+ enabled: true
533
+ }
534
+ ```
647
535
 
648
- If `setup` raises an exception, the module is not registered. Featurevisor removes subscriptions created during setup, reports `module_setup_error`, and calls `close` when present.
536
+ Every evaluation has a `:type` and a `:reason`. Others appear when they apply:
537
+
538
+ - `:feature_key`, absent for global variables, so check for it before using it
539
+ - `:bucket_key` and `:bucket_value`, from 0 to 100,000, and the `:rule_key` that matched
540
+ - `:enabled`, `:variation` and `:variation_value`
541
+ - `:variable_key`, `:variable_value`, `:variable_schema` and `:variable`, the global variable's definition
542
+ - `:variable_override_key` and `:variable_override_index` when a keyed override matched, and `:variable_override_path` for a nested one
543
+ - `:variable_override_paths`, every override path matched in order, for [accumulating overrides](https://featurevisor.com/docs/mutations/#accumulate-overrides). The singular fields describe the last match
544
+ - `:conditions` when a [root gate](https://featurevisor.com/docs/conditions/) stopped the evaluation
545
+ - `:error` when evaluation failed
546
+
547
+ ### Evaluation reasons
548
+
549
+ [Test specs](https://featurevisor.com/docs/testing/) can assert them.
550
+
551
+ | Reason | Meaning |
552
+ | ----------------------------- | -------------------------------------------------------------------------------- |
553
+ | `feature_not_found` | The feature is not in the datafile |
554
+ | `disabled` | The feature is disabled |
555
+ | `no_variations` | A variation was requested from a feature without variations |
556
+ | `variation_disabled` | A disabled feature returned its `disabledVariationValue` |
557
+ | `variable_not_found` | The feature variable or global variable is not in the datafile |
558
+ | `variable_default` | The variable returned its default value |
559
+ | `variable_composed` | A global variable read its composition sources with no override match |
560
+ | `variable_disabled` | A disabled feature returned the variable's disabled value |
561
+ | `variable_override_variation` | A feature variable override matched inside a variation |
562
+ | `variable_override_rule` | A feature variable override or global variable override matched |
563
+ | `conditions_unmet` | Root conditions did not match. See `:conditions` |
564
+ | `no_match` | No rule, allocation or variation matched, or the bucket fell outside the rollout |
565
+ | `forced` | A `force` entry supplied the result |
566
+ | `sticky` | A sticky value supplied the result |
567
+ | `rule` | A matching rule supplied the result |
568
+ | `allocated` | Bucketing allocated the result |
569
+ | `error` | Evaluation failed. See `:error` |
649
570
 
650
- ```ruby
651
- require 'featurevisor'
571
+ ## Modules
652
572
 
653
- my_custom_module = {
654
- # recommended, and used for duplicate detection/removal
655
- name: 'my-custom-module',
573
+ 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:
656
574
 
657
- # rest of the properties below are all optional per module
575
+ ```ruby
576
+ audit_module = {
577
+ name: 'audit',
658
578
 
659
- # setup once, when the module is registered
660
579
  setup: ->(api) {
661
- revision = api[:get_revision].call
662
-
663
580
  api[:on_diagnostic].call(->(diagnostic) {
664
- puts diagnostic[:message]
581
+ # diagnostics at this module's own level
582
+ })
583
+ api[:report_diagnostic].call({
584
+ level: 'info',
585
+ code: 'module_ready',
586
+ message: "Ready for revision #{api[:get_revision].call}"
665
587
  })
666
588
  },
667
589
 
668
- # before feature or global variable evaluation
669
590
  before_evaluation: ->(options) {
670
- # update context before evaluation
671
- options[:context] = options[:context].merge({
672
- someAdditionalAttribute: 'value'
673
- })
674
- options
591
+ # :type, :feature_key, :variable_key and :context
592
+ options.merge(context: options[:context].merge(plan: 'paid'))
675
593
  },
676
594
 
677
- # after feature or global variable evaluation
678
595
  after_evaluation: ->(evaluation, options) {
679
- reason = evaluation[:reason]
680
- if reason == 'error'
681
- # log error
682
- end
596
+ # log evaluation[:error] when evaluation[:reason] is 'error'
683
597
  evaluation
684
598
  },
685
599
 
686
- # configure bucket key
687
- bucket_key: ->(options) {
688
- # return custom bucket key
689
- options[:bucket_key]
690
- },
600
+ bucket_key: ->(options) { options[:bucket_key] },
691
601
 
692
- # configure bucket value (between 0 and 100,000)
693
- bucket_value: ->(options) {
694
- # return custom bucket value
695
- options[:bucket_value]
696
- },
602
+ # between 0 and 100,000
603
+ bucket_value: ->(options) { options[:bucket_value] },
697
604
 
698
- # cleanup when module is removed or SDK is closed
699
605
  close: -> {
700
- # cleanup here
606
+ # clean up when the instance closes
701
607
  }
702
608
  }
703
609
  ```
704
610
 
705
- The module API passed to `setup` exposes:
611
+ `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.
706
612
 
707
- - `get_revision`
708
- - `on_diagnostic`
709
- - `report_diagnostic`
613
+ `before_evaluation` also runs when a [schema](#schemas) 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.
710
614
 
711
- ### Registering modules
615
+ 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.
712
616
 
713
- You can register modules at the time of SDK initialization:
617
+ 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.
714
618
 
715
- ```ruby
716
- require 'featurevisor'
619
+ ### Dependency evaluations
620
+
621
+ [Conditions](https://featurevisor.com/docs/conditions/) and [composition members](https://featurevisor.com/docs/variables/#compose-values) 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.
622
+
623
+ 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.
717
624
 
625
+ ### Register a module
626
+
627
+ Pass modules when creating the instance, or add them later:
628
+
629
+ ```ruby
718
630
  f = Featurevisor.create_featurevisor(
719
- modules: [my_custom_module]
631
+ modules: [audit_module]
720
632
  )
633
+
634
+ remove = f.add_module(tracking_module)
635
+
636
+ # later
637
+ remove.call
638
+ f.remove_module('audit')
721
639
  ```
722
640
 
723
- Or after initialization:
641
+ ### Read the datafile from a module
642
+
643
+ A package, such as [schemas](#schemas), reads the datafile through the API `setup` receives:
644
+
645
+ - `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 as `schemas`, with symbol keys. Treat it as read only. `api[:get_entry_keys]` lists a section's keys.
646
+ - `api[:match_conditions]` answers the package's own conditions with the instance's engine, segments and feature leaves included. Its `readers` answer leaves only the package knows, such as `input`, returning `Featurevisor::Conditions.missing_value` for no value.
647
+ - `api[:evaluate].call({ type:, key:, context: }) { |scope| ... }` evaluates the package's own entry as a getter evaluates a flag. Every module's `before_evaluation` runs first, with `type` and `key` naming the entry, and the conditions the block answers with `scope.match_conditions(conditions, readers)` read the context the modules leave, in one dependency session. The block's result is returned.
648
+
649
+ 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.
650
+
651
+ ## Schemas
652
+
653
+ Schemas validate data against the [schemas](https://featurevisor.com/docs/schemas/#validate-application-data) your datafiles deliver, with the instance you already have, and the same rules, messages and conditions as `@featurevisor/schemas` in JavaScript.
654
+
655
+ Schemas are experimental, so their API may change in a minor release, as in JavaScript.
656
+
657
+ ### Create a schemas instance
658
+
659
+ They are a separate gem, released with the same version as the SDK:
724
660
 
725
661
  ```ruby
726
- remove_module = f.add_module(my_custom_module)
662
+ gem 'featurevisor-schemas', '~> 4.1'
663
+ ```
727
664
 
728
- # remove later by calling the returned function
729
- remove_module.call
665
+ Create it from the SDK instance. Call it `s`, as the SDK instance is `f`:
730
666
 
731
- # or remove by name
732
- f.remove_module('my-custom-module')
667
+ ```ruby
668
+ require 'featurevisor-schemas'
669
+
670
+ s = Featurevisor::Schemas.create(f)
733
671
  ```
734
672
 
735
- ## Child instance
673
+ It holds no copy of the schemas. Every call reads the datafile `f` has now, so a [new datafile](#update-the-datafile) applies at the next validation. Compiled schemas are kept until a datafile changes them, and handles are safe to share between threads.
674
+
675
+ ### Validate a value
676
+
677
+ ```ruby
678
+ value = {
679
+ email: 'user-1@example.com',
680
+ displayName: 'A',
681
+ country: 'nl'
682
+ }
683
+
684
+ result = s.validate('signUp', value)
685
+
686
+ unless result.valid?
687
+ # show result.issues beside the form's fields
688
+ end
689
+ ```
690
+
691
+ - `s.validate(key, value)` returns a result with the value itself and its `issues`. It never coerces, fills defaults or strips keys.
692
+ - `s.valid?(key, value)` returns a boolean.
693
+ - `s.parse(key, value)` returns the value, or raises `Featurevisor::Schemas::ValidationError`, for a controller or a script that wants a value or a stop.
694
+ - All three take `context:`, merged over the instance's, for the [conditions](https://featurevisor.com/docs/schemas/#read-the-context) a schema's rules read.
695
+ - A validation runs as the schema's own evaluation, so a [module](#modules)'s `before_evaluation` sees it, with `type` `schema` and the schema's `key`, and context the module adds reaches every condition, as it does for flags.
696
+ - `s.keys` lists the schemas the datafile has, and `s.key?(key)` says whether it has one.
697
+
698
+ A value can be hashes with string or symbol keys, arrays and primitives, or a `Struct`.
699
+
700
+ A key the datafile does not have fails closed, with one `schemaNotFound` issue, and a `schema_not_found` [diagnostic](#diagnostics) 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.
701
+
702
+ ### Read the issues
736
703
 
737
- A child snapshots the parent keys that exist when it is spawned. Child values win for those keys. Parent keys introduced later are still inherited. Calling `close` removes both child-owned listeners and subscriptions delegated to the parent.
704
+ 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`.
738
705
 
739
- When dealing with purely client-side applications, it is understandable that there is only one user involved, like in browser or mobile applications.
706
+ Validation reports every issue it finds, so a form can mark every field at once. An issue about a field with a [title](https://featurevisor.com/docs/schemas/#title-the-fields) carries it in `params[:title]`, and one whose rule a [mutation](https://featurevisor.com/docs/schemas/#mutations) set names it in `mutation`.
740
707
 
741
- But when using Featurevisor SDK in server-side applications, where a single server instance can handle multiple user requests simultaneously, it is important to isolate the context for each request.
708
+ | Code | Raised when |
709
+ | ---------------------------------- | --------------------------------------------------------------------- |
710
+ | `type` | The value has another type |
711
+ | `const`, `enum` | The value is not one allowed |
712
+ | `minimum`, `maximum` | A number is out of range |
713
+ | `minLength`, `maxLength` | A string is too short or too long |
714
+ | `pattern`, `format` | A string has the wrong shape |
715
+ | `minItems`, `maxItems` | An array has too few or too many items |
716
+ | `uniqueItems` | An array repeats an item |
717
+ | `required`, `additionalProperties` | A key is missing, or there is one it does not allow |
718
+ | `oneOf` | No branch matches, or more than one does |
719
+ | `refine` | An `issues` entry matches, or a [check in code](#check-in-code) fails |
720
+ | `refineError` | A check in code raises, or the schema itself cannot be applied |
721
+ | `schemaNotFound` | The datafile has no such schema or field |
742
722
 
743
- That's where child instances come in handy:
723
+ `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.
724
+
725
+ ### Get a handle
726
+
727
+ 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:
744
728
 
745
729
  ```ruby
746
- child_f = f.spawn({
747
- # user or request specific context
748
- userId: '123'
749
- })
730
+ sign_up = s.get('signUp')
750
731
  ```
751
732
 
752
- Now you can pass the child instance where your individual request is being handled, and you can continue to evaluate features targeting that specific user alone:
733
+ A handle is stable, and reads the current datafile whenever it is used, so keep one for the life of the application.
734
+
735
+ | Member | What it is |
736
+ | ------------------------------------------- | ---------------------------------------------------------------------------------------------------------------------- |
737
+ | `validate`, `valid?`, `parse` | As on `s`, without the key |
738
+ | `field(path)` | The handle of one field, such as `field('displayName')` |
739
+ | `fields` | An object's fields' handles, in [order](#read-annotations), each with its `name` |
740
+ | `constraints`, `field_constraints` | HTML validation attributes, and `field_constraints` by field path on an object, [below](#read-constraints-and-choices) |
741
+ | `options`, `field_options`, `option(value)` | Its choices, `field_options` by field path on an object, and one choice by value |
742
+ | `render_as` | What its rules say the field renders as, such as `'select'` |
743
+ | `annotations` | Its [annotations](#read-annotations) |
744
+ | `with_input(input)` | The same handle with an [input](#follow-the-values-typed-so-far) |
745
+ | `reads` | The fields its rules' conditions read |
746
+ | `subscribe { }` | A call when a [new datafile](#listen-for-changes) changes the schema |
747
+ | `key`, `path`, `name` | The schema's key, and the field's path and own name |
748
+
749
+ `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`.
750
+
751
+ ### Read constraints and choices
752
+
753
+ `constraints` are named after HTML attributes:
753
754
 
754
755
  ```ruby
755
- is_enabled = child_f.is_enabled('my_feature')
756
- variation = child_f.get_variation('my_feature')
757
- variable_value = child_f.get_variable('my_feature', 'my_variable')
758
- global_value = child_f.get_variable('welcomeMessage')
756
+ sign_up.field('displayName').constraints
757
+ # required: true, min_length: 2, max_length: 40
758
+
759
+ sign_up.field('displayName').constraints.attributes
760
+ # { required: true, minlength: 2, maxlength: 40 }, for a view
759
761
  ```
760
762
 
761
- Similar to parent SDK, child instances also support several additional methods:
763
+ - `required`, when the key is required, so an input left empty fails. A key `required` lists counts, whether or not `properties` holds it, so an object with `additionalProperties` only, or none at all, still reports each missing key as `required`
764
+ - `min_length` and `max_length`, from the same rules on a string
765
+ - `min` and `max`, from `minimum` and `maximum` on a number
766
+ - `step` of 1, for an `integer`
767
+ - `multiple`, for an array, such as a multiple select
762
768
 
763
- - `set_context`
764
- - `set_sticky_features`
765
- - `set_sticky_variables`
766
- - `evaluate_flag`
767
- - `is_enabled`
768
- - `evaluate_variation`
769
- - `get_variation`
770
- - `evaluate_variable`
771
- - `get_variable`
772
- - `get_variable_boolean`
773
- - `get_variable_string`
774
- - `get_variable_integer`
775
- - `get_variable_double`
776
- - `get_variable_array`
777
- - `get_variable_object`
778
- - `get_variable_json`
779
- - `get_feature_evaluations`
780
- - `get_variable_evaluations`
781
- - `on`
782
- - `close`
769
+ `options` lists a field's choices in the order of its rules, each with what its [annotations](https://featurevisor.com/docs/schemas/#label-the-choices) say, and `option(value)` finds one, for showing a value saved earlier:
783
770
 
784
- ## Close
771
+ ```ruby
772
+ country = sign_up.field('country')
785
773
 
786
- Both primary and child instances support a `.close()` method, that removes forgotten event listeners (via `on` method) and cleans up any potential memory leaks.
774
+ country.options # nl, de and be, each with its fields
775
+ country.option('nl').title # 'Netherlands'
776
+ country.option('fr') # nil
777
+ ```
778
+
779
+ A 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.
780
+
781
+ ### Read annotations
782
+
783
+ A handle's `annotations` are its node's own, and `fields` gives an object's fields in its `order`:
787
784
 
788
785
  ```ruby
789
- f.close()
786
+ sign_up.annotations['title'] # 'Create your account'
787
+
788
+ sign_up.fields.map(&:path)
789
+ # ['displayName', 'email', 'country']
790
790
  ```
791
791
 
792
- ## CLI usage
792
+ `default` is the value a form starts a field with, and a handle from `with_input` has the one a [mutation sets](https://featurevisor.com/docs/schemas/#start-a-field-with-a-value). 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](https://featurevisor.com/docs/schemas/#annotations) on Schemas writes them.
793
793
 
794
- This package also provides a CLI tool for running your Featurevisor [project](https://featurevisor.com/docs/projects/)'s test specs and benchmarking against this Ruby SDK.
794
+ ### Follow the values typed so far
795
795
 
796
- - Global installation: you can access it as `featurevisor`
797
- - Local installation: you can access it as `bundle exec featurevisor`
798
- - From this repository: you can access it as `bin/featurevisor`
796
+ 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](https://featurevisor.com/docs/schemas/#mutations) that match it applied, so a tax ID shows as required once a business account is chosen:
799
797
 
800
- ### Test
798
+ ```ruby
799
+ values = {
800
+ accountType: 'business',
801
+ country: 'nl'
802
+ }
803
+
804
+ sign_up.field('taxId').constraints.required # false
805
+ sign_up.with_input(values).field('taxId').constraints.required # true
806
+ ```
801
807
 
802
- Learn more about testing [here](https://featurevisor.com/docs/testing/).
808
+ Every 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.
803
809
 
804
- ```bash
805
- $ bundle exec featurevisor test --projectDirectoryPath="/absolute/path/to/your/featurevisor/project"
810
+ ### Choose the messages
811
+
812
+ `messages:` on `create` words every schema's issues, per code, as a template or a lambda of the params:
813
+
814
+ ```ruby
815
+ s = Featurevisor::Schemas.create(
816
+ f,
817
+ messages: {
818
+ required: 'This field is required',
819
+ maxLength: ->(params, info) { "#{params[:length]} of #{params[:maxLength]} characters" }
820
+ }
821
+ )
806
822
  ```
807
823
 
808
- Additional options that are available:
824
+ `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:
809
825
 
810
- ```bash
811
- $ bundle exec featurevisor test \
812
- --projectDirectoryPath="/absolute/path/to/your/featurevisor/project" \
813
- --quiet|--verbose \
814
- --onlyFailures \
815
- --keyPattern="myFeatureKey" \
816
- --assertionPattern="#1"
826
+ 1. A check in code's own message, then the form's.
827
+ 2. The schema's own, and then the `message` of its [issues](https://featurevisor.com/docs/schemas/#issues) entry.
828
+ 3. The application's, from `messages:` on `create`.
829
+ 4. The default, in English.
830
+
831
+ `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:
832
+
833
+ ```ruby
834
+ s = Featurevisor::Schemas.create(
835
+ f,
836
+ translate: ->(issue, info) { I18n.t(issue.message, **issue.params, default: nil) }
837
+ )
817
838
  ```
818
839
 
819
- The Ruby test runner builds base datafiles and Target datafiles in memory via `npx featurevisor build --json`. When an assertion contains `target`, it is evaluated against the matching Target datafile.
840
+ ### Check in code
820
841
 
821
- All three commands accept repeatable `--target=<target>` options. `test` builds only the selected Target datafiles and runs untargeted assertions plus assertions for those targets. `benchmark` and `assess-distribution` run independently against every selected Target datafile. Without `--target`, existing project-wide behaviour is preserved. Project definitions, test specs, Target discovery, and datafile generation continue to come from the Node.js CLI.
842
+ 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:
822
843
 
823
- ### Test against local monorepo's example-1
844
+ ```ruby
845
+ sign_up = s.get('signUp', refine: [
846
+ Featurevisor::Schemas::Refinement.new(
847
+ key: 'nameAvailable',
848
+ path: 'displayName',
849
+ check: ->(display_name, info) { !User.exists?(display_name: display_name) },
850
+ message: 'That display name is taken'
851
+ )
852
+ ])
853
+
854
+ result = sign_up.validate(value)
855
+ ```
824
856
 
825
- ```bash
826
- $ cd /absolute/path/to/featurevisor-ruby
827
- $ bundle exec ruby bin/featurevisor test --projectDirectoryPath=../featurevisor/examples/example-1 --onlyFailures
828
- $ make test-example-1
857
+ - `check` gets the value at its path, and `info` with the whole `input` and the `context`, where `info.read('country')` reads another field. It returns `true` when the value passes.
858
+ - 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.
859
+ - Without a `path`, the check gets the whole value, and runs only when the value has no issue at all. `reads` names other fields whose issues hold it back too, such as `items` for a check of an order's total.
860
+ - Its issue has code `refine` and `params[:refine]` `'nameAvailable'`, with the field's title. A check that raises gives `refineError`, and validation fails closed.
861
+ - Checks run in order, synchronously.
862
+
863
+ ### Options from your application
864
+
865
+ 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:
866
+
867
+ ```ruby
868
+ cities = Featurevisor::Schemas::OptionSource.new(
869
+ key: 'cities',
870
+ path: 'city',
871
+ reads: ['country'],
872
+ search: ->(query, info) { City.where(country: info.read('country')).search(query).map(&:name) },
873
+ lookup: ->(city, info) { City.find_by(country: info.read('country'), name: city)&.then { |found| { title: found.name } } },
874
+ message: 'Choose a city from the list'
875
+ )
876
+
877
+ sign_up = s.get('signUp', option_sources: [cities])
878
+ city = sign_up.with_input({ country: 'nl' }).field('city')
879
+
880
+ city.search('am')
881
+ # Amsterdam and Amersfoort
829
882
  ```
830
883
 
831
- ### Benchmark
884
+ - `search` returns choices shaped like `options`, or values alone. A handle's `search` passes it the values given to `with_input`, so the cities follow the country. `searchable?` says whether a field has one.
885
+ - `lookup` returns the choice for a value, `true` when it carries nothing more, or `nil` when there is none. A handle's `lookup(value)` returns the schema's own choice first, then the source's.
886
+ - Validation runs `lookup` as a [check in code](#check-in-code), after the schema's rules, only for a value that is there, and not while a field `reads` names has an issue. A value it cannot find has code `enum`, worded by `message`.
832
887
 
833
- Learn more about benchmarking [here](https://featurevisor.com/docs/cli/#benchmarking).
888
+ ### Validate on the server
834
889
 
835
- ```bash
836
- $ bundle exec featurevisor benchmark \
837
- --projectDirectoryPath="/absolute/path/to/your/featurevisor/project" \
838
- --environment="production" \
839
- --feature="myFeatureKey" \
840
- --context='{"country": "nl"}' \
841
- --n=1000
890
+ `parse` answers a request with a value or a `ValidationError`, whose `flatten` gives the issues by field:
891
+
892
+ ```ruby
893
+ class SignUpsController < ApplicationController
894
+ def create
895
+ value = Featurevisor.schemas.parse('signUp', params.to_unsafe_h)
896
+ render json: create_account(value)
897
+ rescue Featurevisor::Schemas::ValidationError => error
898
+ render json: error.flatten, status: :bad_request
899
+ end
900
+ end
842
901
  ```
843
902
 
844
- ### Assess distribution
903
+ `Featurevisor.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.
845
904
 
846
- Learn more about assessing distribution [here](https://featurevisor.com/docs/cli/#assess-distribution).
905
+ ### Listen for changes
847
906
 
848
- ```bash
849
- $ bundle exec featurevisor assess-distribution \
850
- --projectDirectoryPath="/absolute/path/to/your/featurevisor/project" \
851
- --environment=production \
852
- --feature=foo \
853
- --variation \
854
- --context='{"country": "nl"}' \
855
- --populateUuid=userId \
856
- --populateUuid=deviceId \
857
- --n=1000
907
+ `subscribe` calls its block when a new datafile changes the schema, through a schema it references too, and returns a lambda that stops it:
908
+
909
+ ```ruby
910
+ stop = s.get('signUp').field('country').subscribe { render_choices }
911
+ ```
912
+
913
+ A datafile whose schema is unchanged calls nothing. `s.close` stops every listener the instance started and removes its module from the Featurevisor instance.
914
+
915
+ ### Patterns
916
+
917
+ 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.
918
+
919
+ ### Failing closed
920
+
921
+ A schema that fails values closed says why with an `error` [diagnostic](#diagnostics), once per datafile revision, so a new datafile reports again:
922
+
923
+ - `schema_pattern_unsupported`, for a pattern that does not compile.
924
+ - `schema_mutation_error`, with `refineError`, for a mutation whose operations cannot be applied.
925
+ - `schema_reference_depth`, with `refineError`. 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 reads `Schema "tree" fails the value closed, since the value is nested more than 128 references deep.`
926
+ - `schema_check_error`, with `refineError`, for a [check in code](#check-in-code) or an option source's `lookup` that raises. Its `details` hold `schemaKey`, `check`, the check's key, and `path`, the check's path as written or an empty string, and the diagnostic carries the `originalError`. It is reported once per schema and check.
927
+
928
+ ### Fields validated alone
929
+
930
+ 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.
931
+
932
+ The message translator, `translate:`, runs last, once mutations have named the issues whose rules they set or changed, so it sees `issue.mutation`.
933
+
934
+ ## Close
935
+
936
+ `close` removes event listeners and closes modules, on the instance and on a child. Closing twice does nothing more:
937
+
938
+ ```ruby
939
+ f.close
858
940
  ```
859
941
 
942
+ Ruby collects unreachable cycles, but an instance your application still references stays alive, so close instances and children when you are done with them.
943
+
860
944
  ## OpenFeature
861
945
 
862
946
  The OpenFeature provider is published as a separate gem. This keeps OpenFeature code and dependencies out of applications that only use the Featurevisor SDK.
@@ -866,10 +950,10 @@ The provider currently requires Ruby 3.4 or newer because that is the minimum ve
866
950
  Install the provider:
867
951
 
868
952
  ```ruby
869
- gem "featurevisor-openfeature", "~> 3.0"
953
+ gem "featurevisor-openfeature", "~> 4.0"
870
954
  ```
871
955
 
872
- It installs the matching `featurevisor` gem and the official `openfeature-sdk` dependency. The provider and base SDK deliberately share the same version, and the provider requires that exact Featurevisor version.
956
+ 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.
873
957
 
874
958
  ```ruby
875
959
  require "featurevisor/openfeature_provider"
@@ -886,15 +970,15 @@ client = OpenFeature::SDK.build_client
886
970
  enabled = client.fetch_boolean_value(
887
971
  flag_key: "checkout",
888
972
  default_value: false,
889
- evaluation_context: OpenFeature::SDK::EvaluationContext.new(targeting_key: "user-123"),
973
+ evaluation_context: OpenFeature::SDK::EvaluationContext.new(targeting_key: "user-4"),
890
974
  )
891
975
  ```
892
976
 
893
- Use `checkout` for a flag, `checkout:variation` for its variation, `checkout:title` for its `title` variable, and `variable:welcomeMessage` for a global variable. Boolean variables use the boolean resolver. Arrays, hashes, and JSON variables use the object resolver.
977
+ 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.
894
978
 
895
979
  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.
896
980
 
897
- You can pass any Featurevisor initialization options directly to the provider. These options are used to create the Featurevisor instance owned by the provider:
981
+ Pass Featurevisor initialization options to the provider to configure the instance it owns:
898
982
 
899
983
  ```ruby
900
984
  provider = Featurevisor::OpenFeatureProvider.new(
@@ -905,19 +989,113 @@ provider = Featurevisor::OpenFeatureProvider.new(
905
989
  )
906
990
  ```
907
991
 
908
- You can also reuse an existing Featurevisor instance:
992
+ Reuse an existing Featurevisor instance:
909
993
 
910
994
  ```ruby
911
- featurevisor = Featurevisor.create_featurevisor(datafile: datafile_content)
912
- provider = Featurevisor::OpenFeatureProvider.new(featurevisor: featurevisor)
995
+ f = Featurevisor.create_featurevisor(datafile: datafile_content)
996
+ provider = Featurevisor::OpenFeatureProvider.new(featurevisor: f)
913
997
  ```
914
998
 
915
- The caller owns an instance passed this way. Provider shutdown does not close it. Call `featurevisor.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.
999
+ 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.
1000
+
1001
+ 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.
1002
+
1003
+ 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.
916
1004
 
917
1005
  See the [OpenFeature provider guide](https://featurevisor.com/docs/sdks/openfeature/) for resolution reasons, errors, metadata, tracking, lifecycle, and providers for other languages.
918
1006
 
1007
+ ## CLI usage
1008
+
1009
+ After adding the gem to your Gemfile as shown in [Install](#install), install it with:
1010
+
1011
+ ```bash
1012
+ bundle install
1013
+ ```
1014
+
1015
+ Use `bundle exec featurevisor` for a bundled installation, `featurevisor` for a global gem installation, or `bin/featurevisor` from this SDK repository.
1016
+
1017
+ The native test runner requires Node.js 24 or later. Install the Node.js CLI in your Featurevisor project:
1018
+
1019
+ ```bash
1020
+ npm install --save-dev @featurevisor/cli@^4.0.0
1021
+ ```
1022
+
1023
+ The 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.
1024
+
1025
+ 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.
1026
+
1027
+ Duplicate targets are evaluated once, at their first position. `--n` and `-n` accept a positive integer.
1028
+
1029
+ ### Test
1030
+
1031
+ 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.
1032
+
1033
+ ```bash
1034
+ bundle exec featurevisor test \
1035
+ --project-directory-path=/path/to/featurevisor-project \
1036
+ --only-failures
1037
+ ```
1038
+
1039
+ See [Testing](https://featurevisor.com/docs/testing/) for authoring specs and [Checks](https://featurevisor.com/docs/testing/#checks) for check syntax and operators.
1040
+
1041
+ Useful test options:
1042
+
1043
+ - `--key-pattern=<pattern>` and `--assertion-pattern=<pattern>` filter tests.
1044
+ - `--entity-type=scenario` selects scenarios, and `--entity-type=schema` schema specs, which validate their values with the `featurevisor-schemas` gem as the JavaScript CLI does. Without that gem, each schema spec case fails asking for it. `--set=<set>` selects one project set. Omitting `--set` runs all sets.
1045
+ - `--case=<id>` reruns one expanded case. Copy the opaque ID or rerun command from a failure report.
1046
+ - `--json --pretty` produces an indented JSON report.
1047
+ - `--coverage` reports observed rule and override selections. `--uncovered` lists features and global variables without associated specs.
1048
+ - `--only-failures`, `--quiet`, `--verbose` and `--show-datafile` control diagnostic output.
1049
+
1050
+ Printed rerun commands use POSIX shell quoting. JSON reports also include raw argument arrays.
1051
+
1052
+ ### Test against local monorepo's example-1
1053
+
1054
+ Contributor instructions are in the [repository development guide](https://github.com/featurevisor/featurevisor-ruby#development).
1055
+
1056
+ ### Benchmark
1057
+
1058
+ 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.
1059
+
1060
+ ```bash
1061
+ bundle exec featurevisor benchmark \
1062
+ --project-directory-path=/path/to/featurevisor-project \
1063
+ --feature=checkout \
1064
+ --context='{"country":"nl"}' \
1065
+ --n=1000
1066
+ ```
1067
+
1068
+ Use `--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](https://featurevisor.com/docs/cli/#benchmarking).
1069
+
1070
+ ### Assess distribution
1071
+
1072
+ ```bash
1073
+ bundle exec featurevisor assess-distribution \
1074
+ --project-directory-path=/path/to/featurevisor-project \
1075
+ --feature=checkout \
1076
+ --populate-uuid=userId \
1077
+ --n=1000
1078
+ ```
1079
+
1080
+ Repeat `--populate-uuid=<key>` to generate UUID values for multiple context attributes. Supply one key per option. See [Assess distribution](https://featurevisor.com/docs/cli/#assess-distribution).
1081
+
1082
+ ## GitHub repositories
1083
+
1084
+ - SDK: [featurevisor/featurevisor-ruby](https://github.com/featurevisor/featurevisor-ruby)
1085
+ - Example application: [featurevisor/featurevisor-example-ruby](https://github.com/featurevisor/featurevisor-example-ruby)
1086
+
919
1087
  <!-- FEATUREVISOR_DOCS_END -->
920
1088
 
1089
+ <a id="getting-aggregate-evaluations"></a>
1090
+ <a id="getting-evaluations"></a>
1091
+
1092
+ The aggregate evaluation reference has moved to [Evaluate everything at once](#evaluate-everything-at-once).
1093
+
1094
+ <a id="sticky-features-and-variables"></a>
1095
+ <a id="sticky"></a>
1096
+
1097
+ The sticky state reference has moved to [Sticky values](#sticky-values).
1098
+
921
1099
  ## Development
922
1100
 
923
1101
  ### Setting up
@@ -932,21 +1110,25 @@ $ make test-base
932
1110
  $ make test-example-1
933
1111
  ```
934
1112
 
1113
+ Run `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.
1114
+
935
1115
  Build and verify both gems with:
936
1116
 
937
1117
  ```bash
938
1118
  $ make build
939
1119
  ```
940
1120
 
941
- The build produces `featurevisor-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.
1121
+ The 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.
942
1122
 
943
1123
  ### Releasing
944
1124
 
1125
+ 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.
1126
+
945
1127
  - Update the shared version in `lib/featurevisor/version.rb`
946
1128
  - Run `bundle install`
947
1129
  - Push commit to `main` branch
948
1130
  - Wait for CI to complete
949
- - Tag the release with the same version number, for example `v3.1.0`
1131
+ - Tag the release with the same version number, for example `vX.Y.Z`
950
1132
  - The workflow verifies that the tag matches the shared version
951
1133
  - The workflow publishes `featurevisor` first, followed by `featurevisor-openfeature`
952
1134