absmartly-sdk 1.3.0 → 1.4.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.
Files changed (44) hide show
  1. checksums.yaml +4 -4
  2. data/.rubocop.yml +2 -1
  3. data/CHANGELOG.md +52 -1
  4. data/Gemfile +4 -0
  5. data/Gemfile.lock +5 -1
  6. data/README.md +463 -145
  7. data/lib/a_b_smartly.rb +118 -22
  8. data/lib/absmartly/version.rb +1 -1
  9. data/lib/absmartly.rb +4 -0
  10. data/lib/audience_matcher.rb +93 -1
  11. data/lib/client.rb +44 -12
  12. data/lib/client_config.rb +3 -1
  13. data/lib/context.rb +1288 -236
  14. data/lib/context_data_result.rb +27 -0
  15. data/lib/context_event_logger.rb +3 -0
  16. data/lib/context_event_logger_callback.rb +1 -1
  17. data/lib/context_publisher.rb +9 -0
  18. data/lib/default_audience_deserializer.rb +2 -2
  19. data/lib/default_context_data_deserializer.rb +3 -3
  20. data/lib/default_context_event_serializer.rb +2 -1
  21. data/lib/default_context_publisher.rb +9 -0
  22. data/lib/default_http_client.rb +26 -5
  23. data/lib/default_http_client_config.rb +6 -1
  24. data/lib/default_variable_parser.rb +1 -1
  25. data/lib/hashing.rb +39 -2
  26. data/lib/json/context_data.rb +26 -3
  27. data/lib/json/experiment.rb +36 -10
  28. data/lib/json/exposure.rb +8 -4
  29. data/lib/json_expr/expr_evaluator.rb +7 -9
  30. data/lib/json_expr/json_expr.rb +23 -17
  31. data/lib/json_expr/operators/and_combinator.rb +2 -1
  32. data/lib/json_expr/operators/in_operator.rb +3 -1
  33. data/lib/json_expr/operators/match_operator.rb +9 -5
  34. data/lib/json_expr/operators/or_combinator.rb +4 -2
  35. data/lib/json_expr/operators/semver_operator.rb +17 -0
  36. data/lib/json_expr/operators/semver_operators.rb +50 -0
  37. data/lib/json_expr/semver_comparator.rb +98 -0
  38. data/lib/publish_error.rb +11 -0
  39. data/lib/scheduled_thread_pool_executor.rb +8 -0
  40. data/lib/type_utils.rb +59 -0
  41. data/lib/variant_assigner.rb +1 -1
  42. metadata +10 -4
  43. data/absmartly.gemspec +0 -45
  44. data/example/example.rb +0 -85
data/README.md CHANGED
@@ -1,161 +1,237 @@
1
- # A/B Smartly SDK
1
+ # ABsmartly Ruby SDK
2
2
 
3
- A/B Smartly Ruby SDK
3
+ Ruby SDK for [ABsmartly](https://www.absmartly.com/) A/B testing platform.
4
4
 
5
5
  ## Compatibility
6
6
 
7
- The A/B Smartly Ruby SDK is compatible with Ruby versions 2.7 and later. For the best performance and code readability, Ruby 3 or later is recommended. This SDK is being constantly tested with the nightly builds of Ruby, to ensure it is compatible with the latest Ruby version.
7
+ The ABsmartly Ruby SDK is compatible with Ruby versions 2.7 and later. For the best performance and code readability, Ruby 3 or later is recommended. This SDK is being constantly tested with the nightly builds of Ruby, to ensure it is compatible with the latest Ruby version.
8
8
 
9
+ ## Installation
10
+
11
+ Install the gem and add to the application's Gemfile by executing:
12
+
13
+ ```bash
14
+ bundle add absmartly-sdk --version "~> 1.4"
15
+ ```
16
+
17
+ If bundler is not being used to manage dependencies, install the gem by executing:
18
+
19
+ ```bash
20
+ gem install absmartly-sdk -v 1.4.0
21
+ ```
9
22
 
10
23
  ## Getting Started
11
24
 
12
- ### Install the SDK
25
+ Please follow the [installation](#installation) instructions before trying the following code.
13
26
 
14
- Install the gem and add to the application's Gemfile by executing:
27
+ ### Initialization
15
28
 
16
- $ bundle add absmartly-sdk
29
+ This example assumes an API Key, an Application, and an Environment have been created in the ABsmartly web console.
17
30
 
18
- If bundler is not being used to manage dependencies, install the gem by executing:
31
+ #### Recommended: Named Parameters (Ruby Keyword Arguments)
32
+
33
+ The simplest and most idiomatic way to initialize the SDK in Ruby:
34
+
35
+ ```ruby
36
+ require 'absmartly'
37
+
38
+ sdk = ABSmartly.new(
39
+ "https://your-company.absmartly.io/v1",
40
+ api_key: "YOUR-API-KEY",
41
+ application: "website",
42
+ environment: "development"
43
+ )
44
+ ```
45
+
46
+ #### With Optional Parameters
19
47
 
20
- $ gem install absmartly-sdk
48
+ ```ruby
49
+ sdk = ABSmartly.new(
50
+ "https://your-company.absmartly.io/v1",
51
+ api_key: "YOUR-API-KEY",
52
+ application: "website",
53
+ environment: "development",
54
+ timeout: 5000, # Connection timeout in milliseconds (default: 3000)
55
+ retries: 3 # Max retry attempts (default: 5)
56
+ )
57
+ ```
21
58
 
22
- ## Import and Initialize the SDK
59
+ #### Alternative: Global Configuration
23
60
 
24
- Once the SDK is installed, it can be initialized in your project.
61
+ For applications that need a single SDK instance shared globally:
25
62
 
26
63
  ```ruby
64
+ require 'absmartly'
65
+
27
66
  Absmartly.configure_client do |config|
28
67
  config.endpoint = "https://your-company.absmartly.io/v1"
29
68
  config.api_key = "YOUR-API-KEY"
30
69
  config.application = "website"
31
70
  config.environment = "development"
32
- config.connect_timeout = 3.0
33
- config.connection_request_timeout = 3.0
34
- config.retry_interval = 0.5
35
- config.max_retries = 5
36
- config.pool_size = 20
37
- config.pool_idle_timeout = 5
38
71
  end
39
72
  ```
40
73
 
74
+ #### Alternative: Full Configuration
75
+
76
+ For use cases where you need custom providers, serializers, or other low-level configurations:
77
+
78
+ ```ruby
79
+ require 'absmartly'
80
+
81
+ client_config = ClientConfig.create
82
+ client_config.endpoint = "https://your-company.absmartly.io/v1"
83
+ client_config.api_key = "YOUR-API-KEY"
84
+ client_config.application = "website"
85
+ client_config.environment = "development"
86
+ client_config.connect_timeout = 3.0
87
+ client_config.connection_request_timeout = 3.0
88
+ client_config.retry_interval = 0.5
89
+ client_config.max_retries = 5
90
+ # Opt in to retrying HTTP statuses (none by default). Retrying a publish after
91
+ # a 5xx may duplicate events the collector already stored.
92
+ client_config.retry_statuses = [502, 503, 504]
93
+ # Opt in to retrying a refused connection on the context fetch (off by default).
94
+ # Each retry waits retry_interval, doubling each time.
95
+ client_config.retry_connection_failures = true
96
+
97
+ sdk_config = ABSmartlyConfig.create
98
+ sdk_config.client = Client.create(client_config)
99
+
100
+ sdk = ABSmartly.create(sdk_config)
101
+ ```
102
+
41
103
  **SDK Options**
42
104
 
43
- | Config | Type | Required? | Default | Description |
44
- | :---------- | :----------------------------------- | :-------: | :-------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
45
- | endpoint | `string` | ✅ | `undefined` | The URL to your API endpoint. Most commonly `"your-company.absmartly.io"` |
46
- | api_key | `string` | ✅ | `undefined` | Your API key which can be found on the Web Console. |
47
- | environment | `"production"` or `"development"` | ✅ | `undefined` | The environment of the platform where the SDK is installed. Environments are created on the Web Console and should match the available environments in your infrastructure. |
48
- | application | `string` | ✅ | `undefined` | The name of the application where the SDK is installed. Applications are created on the Web Console and should match the applications where your experiments will be running. |
49
- | connect_timeout | `number` | ❌ | `3.0` | The socket connection timeout in seconds. |
50
- | connection_request_timeout | `number` | ❌ | `3.0` | The request timeout in seconds. |
51
- | retry_interval | `number` | ❌ | `0.5` | The initial retry interval in seconds (uses exponential backoff). |
52
- | max_retries | `number` | ❌ | `5` | The maximum number of retries before giving up. |
53
- | pool_size | `number` | ❌ | `20` | The number of connections in the HTTP connection pool. |
54
- | pool_idle_timeout | `number` | ❌ | `5` | The time in seconds before idle connections are closed. |
55
- | event_logger | `ContextEventLogger` | ❌ | See "Using a Custom Event Logger" below | A `ContextEventLogger` instance implementing `handle_event(event, data)` to receive SDK events. |
56
-
57
- ### Using a Custom Event Logger
58
-
59
- The A/B Smartly SDK can be instantiated with an event logger used for all
60
- contexts. In addition, an event logger can be specified when creating a
61
- particular context in the context config.
105
+ | Parameter | Type | Required? | Default | Description |
106
+ | :------------------------- | :-------------------------------- | :-------: | :-----: | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
107
+ | endpoint | `String` | ✅ | `nil` | The URL to your API endpoint. Most commonly `"https://your-company.absmartly.io/v1"` (first positional parameter) |
108
+ | api_key | `String` | ✅ | `nil` | Your API key which can be found on the Web Console. |
109
+ | application | `String` | ✅ | `nil` | The name of the application where the SDK is installed. Applications are created on the Web Console and should match the applications where your experiments will be running. |
110
+ | environment | `String` | ✅ | `nil` | The environment of the platform where the SDK is installed. Environments are created on the Web Console and should match the available environments in your infrastructure. |
111
+ | timeout | `Integer` | ❌ | `3000` | The connection and request timeout in milliseconds. Converted to seconds internally. |
112
+ | retries | `Integer` | ❌ | `5` | The maximum number of retries before giving up. |
113
+ | context_event_logger | `ContextEventLogger` | ❌ | `nil` | A `ContextEventLogger` instance implementing `handle_event(event, data)` to receive SDK events. See "Custom Event Logger" below. |
114
+
115
+ ## Creating a New Context
116
+
117
+ ### Basic Context Creation
62
118
 
63
119
  ```ruby
64
- class MyEventLogger < ContextEventLogger
65
- def handle_event(event, data)
66
- case event
67
- when EVENT_TYPE::EXPOSURE
68
- puts "Exposure: #{data}"
69
- when EVENT_TYPE::GOAL
70
- puts "Goal: #{data}"
71
- when EVENT_TYPE::ERROR
72
- puts "Error: #{data}"
73
- when EVENT_TYPE::PUBLISH
74
- puts "Publish: #{data}"
75
- when EVENT_TYPE::READY
76
- puts "Ready: #{data}"
77
- when EVENT_TYPE::REFRESH
78
- puts "Refresh: #{data}"
79
- when EVENT_TYPE::CLOSE
80
- puts "Close"
81
- end
82
- end
83
- end
120
+ sdk = ABSmartly.new(
121
+ "https://your-company.absmartly.io/v1",
122
+ api_key: "YOUR-API-KEY",
123
+ application: "website",
124
+ environment: "development"
125
+ )
126
+
127
+ context_config = ContextConfig.create
128
+ context_config.set_unit('session_id', '5ebf06d8cb5d8137290c4abb64155584fbdb64d8')
129
+
130
+ context = sdk.create_context(context_config)
131
+ ```
132
+
133
+ Or using the global configuration approach:
84
134
 
135
+ ```ruby
85
136
  Absmartly.configure_client do |config|
86
137
  config.endpoint = "https://your-company.absmartly.io/v1"
87
138
  config.api_key = "YOUR-API-KEY"
88
139
  config.application = "website"
89
140
  config.environment = "development"
90
- config.event_logger = MyEventLogger.new
91
141
  end
142
+
143
+ context_config = Absmartly.create_context_config
144
+ context_config.set_unit('session_id', '5ebf06d8cb5d8137290c4abb64155584fbdb64d8')
145
+
146
+ context = Absmartly.create_context(context_config)
92
147
  ```
93
148
 
94
- The data parameter depends on the type of event. Currently, the SDK logs the
95
- following events:
149
+ ### Async Context Creation
150
+
151
+ When you want to avoid blocking the current thread while fetching experiment data, use `create_context_async`. It returns a `Context` immediately and fetches data in a background thread.
152
+
153
+ ```ruby
154
+ sdk = ABSmartly.new(
155
+ "https://your-company.absmartly.io/v1",
156
+ api_key: "YOUR-API-KEY",
157
+ application: "website",
158
+ environment: "development"
159
+ )
160
+
161
+ context_config = ContextConfig.create
162
+ context_config.set_unit('session_id', '5ebf06d8cb5d8137290c4abb64155584fbdb64d8')
96
163
 
97
- | eventName | when | data |
98
- | ------------ | ------------------------------------------------------- | -------------------------------------------- |
99
- | `"error"` | `Context` receives an error | error object thrown |
100
- | `"ready"` | `Context` turns ready | data used to initialize the context |
101
- | `"refresh"` | `Context.refresh()` method succeeds | data used to refresh the context |
102
- | `"publish"` | `Context.publish()` method succeeds | data sent to the A/B Smartly event collector |
103
- | `"exposure"` | `Context.treatment()` method succeeds on first exposure | exposure data enqueued for publishing |
104
- | `"goal"` | `Context.track()` method succeeds | goal data enqueued for publishing |
105
- | `"close"` | `Context.close()` method succeeds the first time | nil |
164
+ context = sdk.create_context_async(context_config)
106
165
 
107
- ## Create a New Context Request
166
+ # Do other work while data is being fetched...
108
167
 
168
+ # Block until the context is ready (or use a timeout)
169
+ context.wait_until_ready
170
+ # context.wait_until_ready(5) # with a 5-second timeout
171
+
172
+ if context.ready?
173
+ treatment = context.treatment('exp_test_experiment')
174
+ end
175
+ ```
176
+
177
+ A `refresh` that was already in flight when the initial fetch failed, and then installs data, recovers the context (a failed `refresh` installs nothing, and a `refresh` called after the context failed is a no-op, as in 1.3.0): it installs the data, clears `failed?` and `ready_error`, and events still queued are published with the next `publish`. Exposures made while the context was failed are unassigned (`assigned: false`, experiment id 0; control unless an override forces a variant), which the collector excludes from analysis; a `publish` made while the context was failed still drops its events, as in 1.3.0. A `refresh` that succeeds before the background fetch lands makes the context ready with the refreshed data; that data is kept when the initial fetch completes later, and the `"ready"` event is logged once the initial fetch completes.
178
+
179
+ Read methods (`treatment`, `peek_treatment`, `variable_value`, `peek_variable_value`, `variable_keys`, `experiments`, `custom_field_keys`, `custom_field_value`) raise `IllegalStateException` ("ABSmartly Context is not yet ready") until the context is ready, and ("ABSmartly Context is closed") after `close` or `finalize` (except `experiments`, which still works after `finalize`). Check `ready?` first. A context whose data fetch failed is ready and failed: reads return control (0) and the caller's defaults.
180
+
181
+ Or using the global configuration approach:
109
182
 
110
183
  ```ruby
111
- context_config = Absmartly.create_context_config
184
+ context = Absmartly.create_context_async(context_config)
185
+ context.wait_until_ready
112
186
  ```
113
187
 
114
- **With Prefetched Data**
188
+ ### With Pre-fetched Data
189
+
190
+ When doing full-stack experimentation with ABsmartly, we recommend creating a context only once on the server-side. Creating a context involves a round-trip to the ABsmartly event collector. We can avoid repeating the round-trip on the client-side by sending the server-side data embedded in the first document.
115
191
 
116
192
  ```ruby
117
- client_config = ClientConfig.new(
118
- endpoint: 'https://your-company.absmartly.io/v1',
119
- api_key: 'YOUR-API-KEY',
120
- application: 'website',
121
- environment: 'development')
193
+ sdk = ABSmartly.new(
194
+ "https://your-company.absmartly.io/v1",
195
+ api_key: "YOUR-API-KEY",
196
+ application: "website",
197
+ environment: "development"
198
+ )
122
199
 
123
- sdk_config = ABSmartlyConfig.create
124
- sdk_config.client = Client.create(client_config)
200
+ context_config = ContextConfig.create
201
+ context_config.set_unit('session_id', '5ebf06d8cb5d8137290c4abb64155584fbdb64d8')
202
+
203
+ server_context = sdk.create_context(context_config)
125
204
 
126
- sdk = Absmartly.create(sdk_config)
205
+ client_context_config = ContextConfig.create
206
+ client_context_config.set_unit('session_id', '5ebf06d8cb5d8137290c4abb64155584fbdb64d8')
207
+
208
+ client_context = sdk.create_context_with(client_context_config, server_context.data)
127
209
  ```
128
210
 
129
- **Refreshing the Context with Fresh Experiment Data**
211
+ ### Refreshing the Context with Fresh Experiment Data
212
+
213
+ For long-running contexts, the context is usually created once when the application is first started. However, any experiments being tracked in your production code, but started after the context was created, will not be triggered.
130
214
 
131
- For long-running contexts, the context is usually created once when the
132
- application is first started. However, any experiments being tracked in your
133
- production code, but started after the context was created, will not be
134
- triggered.
215
+ The `refresh` method can be called manually. The `refresh` method pulls updated experiment data from the ABsmartly collector and will trigger recently started experiments when `treatment` is called again.
135
216
 
136
- Alternatively, the `refresh` method can be called manually. The
137
- `refresh` method pulls updated experiment data from the A/B
138
- Smartly collector and will trigger recently started experiments when
139
- `treatment` is called again.
217
+ ```ruby
218
+ context.refresh
219
+ ```
140
220
 
141
- **Setting Extra Units**
221
+ ### Setting Extra Units
142
222
 
143
- You can add additional units to a context by calling the `set_unit()` or
144
- `set_units()` methods. These methods may be used, for example, when a user
145
- logs in to your application and you want to use the new unit type in the
146
- context.
223
+ You can add additional units to a context by calling the `set_unit` or `set_units` methods. These methods may be used, for example, when a user logs in to your application and you want to use the new unit type in the context.
147
224
 
148
- Please note, you cannot override an already set unit type as that would be
149
- a change of identity and would throw an exception. In this case, you must
150
- create a new context instead. The `set_unit()` and
151
- `set_units()` methods can be called before the context is ready.
225
+ > **Note:** You cannot override an already set unit type as that would be a change of identity and would throw an exception. In this case, you must create a new context instead. The `set_unit` and `set_units` methods can be called before the context is ready.
152
226
 
153
227
  ```ruby
154
228
  context_config.set_unit('session_id', 'bf06d8cb5d8137290c4abb64155584fbdb64d8')
155
229
  context_config.set_unit('user_id', '123456')
156
230
  context = Absmartly.create_context(context_config)
157
231
  ```
158
- or
232
+
233
+ or
234
+
159
235
  ```ruby
160
236
  context_config.set_units(
161
237
  session_id: 'bf06d8cb5d8137290c4abb64155584fbdb64d8',
@@ -166,7 +242,7 @@ context = Absmartly.create_context(context_config)
166
242
 
167
243
  ## Basic Usage
168
244
 
169
- ### Selecting A Treatment
245
+ ### Selecting a Treatment
170
246
 
171
247
  ```ruby
172
248
  treatment = context.treatment('exp_test_experiment')
@@ -180,40 +256,41 @@ end
180
256
 
181
257
  ### Treatment Variables
182
258
 
183
- ```ruby
184
- default_button_color_value = 'red'
259
+ Variables allow you to configure experiment variants dynamically:
185
260
 
186
- context.variable_value('experiment_name', default_button_color_value)
261
+ ```ruby
262
+ default_button_color = 'red'
263
+ button_color = context.variable_value('button.color', default_button_color)
187
264
  ```
188
265
 
266
+ #### Shared variable keys
267
+
268
+ When several experiments define the same variable key, the SDK checks the experiments whose variants define it in experiment id order. The first one the unit is assigned to, overridden in or rule-assigned in wins, and only that experiment is exposed. If the winner's variant does not define the key, `variable_value` returns your default rather than reading a later experiment. If no experiment wins, a held-out unit reads the control value of the first held-out experiment; otherwise your default is returned and no experiment is exposed. `peek_variable_value` follows the same rule without exposing anything.
269
+
189
270
  ### Peek at Treatment Variants
190
271
 
191
- Although generally not recommended, it is sometimes necessary to peek at
192
- a treatment or variable without triggering an exposure. The A/B Smartly
193
- SDK provides a `peek_treatment()` method for that.
272
+ Although generally not recommended, it is sometimes necessary to peek at a treatment or variable without triggering an exposure. The ABsmartly SDK provides `peek_treatment` and `peek_variable_value` methods for that.
194
273
 
195
274
  ```ruby
196
275
  treatment = context.peek_treatment('exp_test_experiment')
197
276
  ```
198
277
 
199
- #### Peeking at variables
278
+ #### Peeking at Variables
200
279
 
201
280
  ```ruby
202
- treatment = context.peek_variable_value('exp_test_experiment')
281
+ button_color = context.peek_variable_value('button.color', 'red')
203
282
  ```
204
283
 
205
284
  ### Overriding Treatment Variants
206
285
 
207
- During development, for example, it is useful to force a treatment for an
208
- experiment. This can be achieved with the `set_override()` and/or `set_overrides()`
209
- methods. These methods can be called before the context is ready.
286
+ During development, for example, it is useful to force a treatment for an experiment. This can be achieved with the `set_override` and/or `set_overrides` methods. These methods can be called before the context is ready.
210
287
 
211
288
  ```ruby
212
- context.set_override("exp_test_experiment", 1) # force variant 1 of treatment
289
+ context.set_override('exp_test_experiment', 1) # force variant 1 of treatment
213
290
 
214
291
  context.set_overrides(
215
- 'exp_test_experiment' => 1,
216
- 'exp_another_experiment' => 0,
292
+ 'exp_test_experiment' => 1,
293
+ 'exp_another_experiment' => 0
217
294
  )
218
295
  ```
219
296
 
@@ -221,70 +298,311 @@ context.set_overrides(
221
298
 
222
299
  ### Context Attributes
223
300
 
224
- Attributes are used to pass meta-data about the user and/or the request.
225
- They can be used later in the Web Console to create segments or audiences.
226
- They can be set using the `set_attribute()` or `set_attributes()`
227
- methods, before or after the context is ready.
301
+ Attributes are used to pass meta-data about the user and/or the request. They can be used later in the Web Console to create segments or audiences. They can be set using the `set_attribute` or `set_attributes` methods, before or after the context is ready.
228
302
 
229
303
  ```ruby
230
- context.set_attribute('session_id', session_id)
304
+ context.set_attribute('user_agent', request.user_agent)
305
+
231
306
  context.set_attributes(
232
- 'customer_age' => 'new_customer'
307
+ customer_age: 'new_customer',
308
+ account_type: 'premium'
233
309
  )
234
310
  ```
235
311
 
312
+ The application and environment configured on the client are available to audience filters and assignment rule conditions as `application` and `environment`. A name that is unset or empty is left out, so a filter on it sees no value. An attribute you set with the same name takes precedence. They are not added to published attributes, since the collector attaches them itself.
313
+
314
+ ### Assignment Rules
315
+
316
+ Experiments can define assignment rules on the Web Console. They are evaluated in order and the first matching rule decides the variant, taking precedence over audience targeting, traffic allocation and custom assignments; only `set_override` beats a rule. Rule-assigned exposures are flagged `ruleOverride` so they are excluded from analysis.
317
+
318
+ - An `assign` rule gives a fixed variant.
319
+ - A `split` rule randomizes the unit over its own percentages, e.g. `20/30/50`. While the experiment's unit is missing, it gives the full-on variant (0 for an experiment that is not full-on); once the unit is set, the rule is re-resolved unless that variant was already exposed.
320
+
321
+ Rule conditions are audience expressions, so they can use your attributes, `application`, `environment` and the `semver_eq`, `semver_gt`, `semver_gte`, `semver_lt` and `semver_lte` operators, e.g. `{"semver_gte": [{"var": "app_version"}, {"value": "2.4.0"}]}`.
322
+
323
+ ### Holdouts
324
+
325
+ Experiments can be covered by holdouts set up on the Web Console. A holdout keeps a share of units out of every experiment it covers, so you can measure the combined effect of those experiments. The SDK handles this for you: no code changes are needed.
326
+
327
+ - A held-out unit gets control (variant 0; for a shared variable key its control value is used only when no other experiment defining the key wins, see [Shared variable keys](#shared-variable-keys)) for each covered experiment, and no exposure is queued for that experiment.
328
+ - The holdout queues its own exposure, once per unit type, the first time the unit sees a covered experiment, whether it is held out or not. Like every exposure, it reaches the collector on `publish` or `close`.
329
+ - A unit held out by any of the holdouts covering an experiment is held out of it.
330
+ - A holdout with three arms holds full-on experiments out only in its first arm, and other experiments in its first two arms.
331
+ - `set_override` and a matching assignment rule still win over a holdout; the holdout's exposure is still queued.
332
+ - Peeking (`peek_treatment`, `peek_variable_value`) never queues exposures.
333
+ - Set the unit before reading a covered experiment. An experiment read with `treatment` or `variable_value` before its unit type is set gets no holdout arm; `set_unit` alone does not change that exposed assignment or expose the holdout for it. A later refresh that changes the experiment or its coverage can rebuild the assignment. The exception is an overridden experiment, as in the Java SDK: its holdout is exposed by the next `variable_value` read after `set_unit` (not by `treatment`); the override still wins.
334
+
236
335
  ### Custom Assignments
237
336
 
238
- Sometimes it may be necessary to override the automatic selection of a
239
- variant. For example, if you wish to have your variant chosen based on
240
- data from an API call. This can be accomplished using the
241
- `set_custom_assignment()` method.
337
+ Sometimes it may be necessary to override the automatic selection of a variant. For example, if you wish to have your variant chosen based on data from an API call. This can be accomplished using the `set_custom_assignment` method.
242
338
 
243
339
  ```ruby
244
340
  chosen_variant = 1
245
341
  context.set_custom_assignment('experiment_name', chosen_variant)
246
342
  ```
247
343
 
248
- If you are running multiple experiments and need to choose different
249
- custom assignments for each one, you can do so using the
250
- `set_custom_assignments()` method.
344
+ If you are running multiple experiments and need to choose different custom assignments for each one, you can do so using the `set_custom_assignments` method.
251
345
 
252
346
  ```ruby
253
- assignments = [
254
- 'experiment_name' => 1,
255
- 'another_experiment_name' => 0,
256
- 'a_third_experiment_name' => 2
257
- ]
347
+ assignments = {
348
+ 'experiment_name' => 1,
349
+ 'another_experiment_name' => 0,
350
+ 'a_third_experiment_name' => 2
351
+ }
258
352
 
259
- context.set_custom_assignments(assignments)
353
+ context.set_custom_assignments(assignments)
260
354
  ```
261
355
 
262
- ### Publish
356
+ ### Tracking Goals
263
357
 
264
- Sometimes it is necessary to ensure all events have been published to the
265
- A/B Smartly collector, before proceeding. You can explicitly call the
266
- `publish()` methods.
358
+ Goals are created in the ABsmartly web console.
267
359
 
360
+ ```ruby
361
+ context.track('payment', {
362
+ item_count: 1,
363
+ total_amount: 1999.99
364
+ })
268
365
  ```
366
+
367
+ ### Publishing Pending Data
368
+
369
+ Sometimes it is necessary to ensure all events have been published to the ABsmartly collector, before proceeding. You can explicitly call the `publish` method.
370
+
371
+ ```ruby
269
372
  context.publish
270
373
  ```
271
374
 
272
- ### Finalize
375
+ ### Finalizing
273
376
 
274
- The `close()` method will ensure all events have been
275
- published to the A/B Smartly collector, like `publish()`, and will also
276
- "seal" the context, throwing an error if any method that could generate
277
- an event is called.
377
+ The `close` method will ensure all events have been published to the ABsmartly collector, like `publish`, and will also "seal" the context, throwing an error if any method that could generate an event is called.
278
378
 
279
- ```
379
+ If the collector rejects the final publish, `close` logs an `"error"` event, drops that batch and still seals the context, as in v1.3.0. Events tracked while that request was in flight are not part of the rejected batch, so `close` sends them before sealing.
380
+
381
+ ```ruby
280
382
  context.close
281
383
  ```
282
384
 
283
- ### Tracking Goals
385
+ `finalize` works like the other ABsmartly SDKs: if the final publish fails it raises the failure (a `StandardError`, so an ordinary `rescue` catches it), the context stays open and the events stay queued, so `finalize` can be called again to retry. It logs the `"finalize"` event instead of `"close"`, and `experiments`, `set_override` and `set_overrides` keep working after it.
386
+
387
+ ```ruby
388
+ begin
389
+ context.finalize
390
+ rescue StandardError => e
391
+ # retry later: the events are still queued
392
+ end
393
+ ```
394
+
395
+ Both sealing methods allow one extra publish for events queued during the first request. If events are still queued after that extra publish (whether it succeeded, or `close` dropped its rejected batch), they stay queued, the context stays open, and the method raises `StandardError` ("Events queued while closing; retry close or finalize"); those events are not sent in the same call, so retry after the producer stops. Otherwise a rejection follows the rules above: `close` logs the error, drops that batch and seals (as in v1.3.0), and `finalize` raises the rejection and stays open.
396
+
397
+ ### Custom Event Logger
398
+
399
+ The ABsmartly SDK can be instantiated with an event logger used for all contexts. In addition, an event logger can be specified when creating a particular context in the context config.
284
400
 
285
401
  ```ruby
286
- context.track(
287
- 'payment',
288
- { item_count: 1, total_amount: 1999.99 }
402
+ class CustomEventLogger < ContextEventLogger
403
+ def handle_event(event, data)
404
+ case event
405
+ when EVENT_TYPE::EXPOSURE
406
+ puts "Exposed to experiment: #{data.name}"
407
+ when EVENT_TYPE::GOAL
408
+ puts "Goal tracked: #{data.name}"
409
+ when EVENT_TYPE::ERROR
410
+ puts "Error: #{data}"
411
+ when EVENT_TYPE::PUBLISH
412
+ puts "Events published: #{data.length} events"
413
+ when EVENT_TYPE::READY
414
+ puts "Context ready with #{data.experiments.length} experiments"
415
+ when EVENT_TYPE::REFRESH
416
+ puts "Context refreshed with #{data.experiments.length} experiments"
417
+ when EVENT_TYPE::CLOSE, EVENT_TYPE::FINALIZE
418
+ puts "Context closed"
419
+ end
420
+ end
421
+ end
422
+
423
+ sdk = ABSmartly.new(
424
+ "https://your-company.absmartly.io/v1",
425
+ api_key: "YOUR-API-KEY",
426
+ application: "website",
427
+ environment: "development",
428
+ context_event_logger: CustomEventLogger.new
289
429
  )
290
430
  ```
431
+
432
+ Or using the global configuration approach:
433
+
434
+ ```ruby
435
+ Absmartly.configure_client do |config|
436
+ config.endpoint = "https://your-company.absmartly.io/v1"
437
+ config.api_key = "YOUR-API-KEY"
438
+ config.application = "website"
439
+ config.environment = "development"
440
+ config.event_logger = CustomEventLogger.new
441
+ end
442
+ ```
443
+
444
+ The data parameter depends on the type of event. Currently, the SDK logs the following events:
445
+
446
+ **Event Types**
447
+
448
+ | Event | When | Data |
449
+ | ----------- | ------------------------------------------------------- | -------------------------------------------- |
450
+ | `Error` | `Context` receives an error | Error object thrown |
451
+ | `Ready` | `Context` turns ready | ContextData used to initialize the context |
452
+ | `Refresh` | `Context.refresh()` method succeeds | ContextData used to refresh the context |
453
+ | `Publish` | `Context.publish()` method succeeds | PublishEvent sent to the collector |
454
+ | `Exposure` | `Context.treatment()` method succeeds on first exposure | Exposure data enqueued for publishing |
455
+ | `Goal` | `Context.track()` method succeeds | GoalAchievement enqueued for publishing |
456
+ | `Close` | `Context.close()` method succeeds the first time | `nil` |
457
+ | `Finalize` | `Context.finalize()` method succeeds the first time | `nil` |
458
+
459
+ ## Platform-Specific Examples
460
+
461
+ ### Using with Ruby on Rails
462
+
463
+ ```ruby
464
+ # config/initializers/absmartly.rb
465
+ require 'absmartly'
466
+
467
+ Absmartly.configure_client do |config|
468
+ config.endpoint = ENV['ABSMARTLY_ENDPOINT']
469
+ config.api_key = ENV['ABSMARTLY_API_KEY']
470
+ config.application = "website"
471
+ config.environment = Rails.env
472
+ end
473
+
474
+ # app/controllers/application_controller.rb
475
+ class ApplicationController < ActionController::Base
476
+ before_action :setup_absmartly_context
477
+ after_action :close_absmartly_context
478
+
479
+ private
480
+
481
+ def setup_absmartly_context
482
+ context_config = Absmartly.create_context_config
483
+ context_config.set_unit('session_id', session.id.to_s)
484
+ context_config.set_unit('user_id', current_user&.id&.to_s) if current_user
485
+
486
+ @absmartly_context = Absmartly.create_context(context_config)
487
+ rescue => e
488
+ Rails.logger.error "ABsmartly context creation failed: #{e.message}"
489
+ @absmartly_context = nil
490
+ end
491
+
492
+ def close_absmartly_context
493
+ @absmartly_context&.close
494
+ end
495
+ end
496
+
497
+ # app/controllers/products_controller.rb
498
+ class ProductsController < ApplicationController
499
+ def show
500
+ treatment = @absmartly_context&.treatment('exp_product_layout') || 0
501
+
502
+ if treatment == 0
503
+ render 'show_control'
504
+ else
505
+ render 'show_treatment'
506
+ end
507
+ end
508
+ end
509
+ ```
510
+
511
+ ### Using with Sinatra
512
+
513
+ ```ruby
514
+ require 'sinatra'
515
+ require 'absmartly'
516
+
517
+ configure do
518
+ Absmartly.configure_client do |config|
519
+ config.endpoint = ENV['ABSMARTLY_ENDPOINT']
520
+ config.api_key = ENV['ABSMARTLY_API_KEY']
521
+ config.application = "website"
522
+ config.environment = ENV['RACK_ENV']
523
+ end
524
+ end
525
+
526
+ use Rack::Session::Cookie, secret: ENV['SESSION_SECRET']
527
+
528
+ before do
529
+ context_config = Absmartly.create_context_config
530
+ context_config.set_unit('session_id', session[:session_id] ||= SecureRandom.uuid)
531
+
532
+ @absmartly_context = Absmartly.create_context(context_config)
533
+ end
534
+
535
+ after do
536
+ @absmartly_context&.close
537
+ end
538
+
539
+ get '/' do
540
+ treatment = @absmartly_context.treatment('exp_test_experiment')
541
+
542
+ if treatment == 0
543
+ erb :control
544
+ else
545
+ erb :treatment
546
+ end
547
+ end
548
+ ```
549
+
550
+ ### Using with Rack Middleware
551
+
552
+ ```ruby
553
+ # config.ru
554
+ require 'absmartly'
555
+
556
+ class ABsmartlyMiddleware
557
+ def initialize(app)
558
+ @app = app
559
+
560
+ Absmartly.configure_client do |config|
561
+ config.endpoint = ENV['ABSMARTLY_ENDPOINT']
562
+ config.api_key = ENV['ABSMARTLY_API_KEY']
563
+ config.application = "website"
564
+ config.environment = ENV['RACK_ENV']
565
+ end
566
+ end
567
+
568
+ def call(env)
569
+ request = Rack::Request.new(env)
570
+
571
+ context_config = Absmartly.create_context_config
572
+ context_config.set_unit('session_id', request.session['session_id'])
573
+
574
+ context = Absmartly.create_context(context_config)
575
+
576
+ env['absmartly.context'] = context
577
+
578
+ begin
579
+ @app.call(env)
580
+ ensure
581
+ context.close
582
+ end
583
+ end
584
+ end
585
+
586
+ use ABsmartlyMiddleware
587
+ run MyApp
588
+ ```
589
+
590
+ ## About A/B Smartly
591
+
592
+ **A/B Smartly** is the leading provider of state-of-the-art, on-premises, full-stack experimentation platforms for engineering and product teams that want to confidently deploy features as fast as they can develop them.
593
+ A/B Smartly's real-time analytics helps engineering and product teams ensure that new features will improve the customer experience without breaking or degrading performance and/or business metrics.
594
+
595
+ ### Have a look at our growing list of clients and SDKs:
596
+ - [JavaScript SDK](https://www.github.com/absmartly/javascript-sdk)
597
+ - [Java SDK](https://www.github.com/absmartly/java-sdk)
598
+ - [PHP SDK](https://www.github.com/absmartly/php-sdk)
599
+ - [Swift SDK](https://www.github.com/absmartly/swift-sdk)
600
+ - [Vue2 SDK](https://www.github.com/absmartly/vue2-sdk)
601
+ - [Vue3 SDK](https://www.github.com/absmartly/vue3-sdk)
602
+ - [React SDK](https://www.github.com/absmartly/react-sdk)
603
+ - [Python3 SDK](https://www.github.com/absmartly/python3-sdk)
604
+ - [Go SDK](https://www.github.com/absmartly/go-sdk)
605
+ - [Ruby SDK](https://www.github.com/absmartly/ruby-sdk) (this package)
606
+ - [.NET SDK](https://www.github.com/absmartly/dotnet-sdk)
607
+ - [Dart SDK](https://www.github.com/absmartly/dart-sdk)
608
+ - [Flutter SDK](https://www.github.com/absmartly/flutter-sdk)