absmartly-sdk 1.3.0.pre.1 → 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 (45) hide show
  1. checksums.yaml +4 -4
  2. data/.rubocop.yml +2 -1
  3. data/.ruby-version +1 -1
  4. data/CHANGELOG.md +55 -1
  5. data/Gemfile +4 -0
  6. data/Gemfile.lock +39 -32
  7. data/README.md +461 -139
  8. data/lib/a_b_smartly.rb +118 -22
  9. data/lib/absmartly/version.rb +1 -1
  10. data/lib/absmartly.rb +4 -0
  11. data/lib/audience_matcher.rb +93 -1
  12. data/lib/client.rb +44 -12
  13. data/lib/client_config.rb +3 -1
  14. data/lib/context.rb +1302 -222
  15. data/lib/context_data_result.rb +27 -0
  16. data/lib/context_event_logger.rb +3 -0
  17. data/lib/context_event_logger_callback.rb +1 -1
  18. data/lib/context_publisher.rb +9 -0
  19. data/lib/default_audience_deserializer.rb +2 -2
  20. data/lib/default_context_data_deserializer.rb +3 -3
  21. data/lib/default_context_event_serializer.rb +2 -1
  22. data/lib/default_context_publisher.rb +9 -0
  23. data/lib/default_http_client.rb +28 -7
  24. data/lib/default_http_client_config.rb +10 -1
  25. data/lib/default_variable_parser.rb +1 -1
  26. data/lib/hashing.rb +39 -2
  27. data/lib/json/context_data.rb +26 -3
  28. data/lib/json/experiment.rb +36 -10
  29. data/lib/json/exposure.rb +8 -4
  30. data/lib/json_expr/expr_evaluator.rb +7 -9
  31. data/lib/json_expr/json_expr.rb +23 -17
  32. data/lib/json_expr/operators/and_combinator.rb +2 -1
  33. data/lib/json_expr/operators/in_operator.rb +3 -1
  34. data/lib/json_expr/operators/match_operator.rb +9 -5
  35. data/lib/json_expr/operators/or_combinator.rb +4 -2
  36. data/lib/json_expr/operators/semver_operator.rb +17 -0
  37. data/lib/json_expr/operators/semver_operators.rb +50 -0
  38. data/lib/json_expr/semver_comparator.rb +98 -0
  39. data/lib/publish_error.rb +11 -0
  40. data/lib/scheduled_thread_pool_executor.rb +8 -0
  41. data/lib/type_utils.rb +59 -0
  42. data/lib/variant_assigner.rb +1 -1
  43. metadata +14 -5
  44. data/absmartly.gemspec +0 -45
  45. data/example/example.rb +0 -85
data/README.md CHANGED
@@ -1,157 +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
71
  end
37
72
  ```
38
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
+
39
103
  **SDK Options**
40
104
 
41
- | Config | Type | Required? | Default | Description |
42
- | :---------- | :----------------------------------- | :-------: | :-------------------------------------: | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
43
- | endpoint | `string` | ✅ | `undefined` | The URL to your API endpoint. Most commonly `"your-company.absmartly.io"` |
44
- | api_key | `string` | ✅ | `undefined` | Your API key which can be found on the Web Console. |
45
- | 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. |
46
- | 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. |
47
- | connect_timeout | `number` | ❌ | `3.0` | The socket connection timeout in seconds. |
48
- | connection_request_timeout | `number` | ❌ | `3.0` | The request timeout in seconds. |
49
- | retry_interval | `number` | ❌ | `0.5` | The initial retry interval in seconds (uses exponential backoff). |
50
- | max_retries | `number` | ❌ | `5` | The maximum number of retries before giving up. |
51
- | event_logger | `ContextEventLogger` | ❌ | See "Using a Custom Event Logger" below | A `ContextEventLogger` instance implementing `handle_event(event, data)` to receive SDK events. |
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. |
52
114
 
53
- ### Using a Custom Event Logger
115
+ ## Creating a New Context
54
116
 
55
- The A/B Smartly SDK can be instantiated with an event logger used for all
56
- contexts. In addition, an event logger can be specified when creating a
57
- particular context in the context config.
117
+ ### Basic Context Creation
58
118
 
59
119
  ```ruby
60
- class MyEventLogger < ContextEventLogger
61
- def handle_event(event, data)
62
- case event
63
- when EVENT_TYPE::EXPOSURE
64
- puts "Exposure: #{data}"
65
- when EVENT_TYPE::GOAL
66
- puts "Goal: #{data}"
67
- when EVENT_TYPE::ERROR
68
- puts "Error: #{data}"
69
- when EVENT_TYPE::PUBLISH
70
- puts "Publish: #{data}"
71
- when EVENT_TYPE::READY
72
- puts "Ready: #{data}"
73
- when EVENT_TYPE::REFRESH
74
- puts "Refresh: #{data}"
75
- when EVENT_TYPE::CLOSE
76
- puts "Close"
77
- end
78
- end
79
- 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:
80
134
 
135
+ ```ruby
81
136
  Absmartly.configure_client do |config|
82
137
  config.endpoint = "https://your-company.absmartly.io/v1"
83
138
  config.api_key = "YOUR-API-KEY"
84
139
  config.application = "website"
85
140
  config.environment = "development"
86
- config.event_logger = MyEventLogger.new
87
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)
88
147
  ```
89
148
 
90
- The data parameter depends on the type of event. Currently, the SDK logs the
91
- 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.
92
152
 
93
- | eventName | when | data |
94
- | ------------ | ------------------------------------------------------- | -------------------------------------------- |
95
- | `"error"` | `Context` receives an error | error object thrown |
96
- | `"ready"` | `Context` turns ready | data used to initialize the context |
97
- | `"refresh"` | `Context.refresh()` method succeeds | data used to refresh the context |
98
- | `"publish"` | `Context.publish()` method succeeds | data sent to the A/B Smartly event collector |
99
- | `"exposure"` | `Context.treatment()` method succeeds on first exposure | exposure data enqueued for publishing |
100
- | `"goal"` | `Context.track()` method succeeds | goal data enqueued for publishing |
101
- | `"close"` | `Context.close()` method succeeds the first time | nil |
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')
102
163
 
103
- ## Create a New Context Request
164
+ context = sdk.create_context_async(context_config)
104
165
 
166
+ # Do other work while data is being fetched...
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:
105
182
 
106
183
  ```ruby
107
- context_config = Absmartly.create_context_config
184
+ context = Absmartly.create_context_async(context_config)
185
+ context.wait_until_ready
108
186
  ```
109
187
 
110
- **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.
111
191
 
112
192
  ```ruby
113
- client_config = ClientConfig.new(
114
- endpoint: 'https://your-company.absmartly.io/v1',
115
- api_key: 'YOUR-API-KEY',
116
- application: 'website',
117
- 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
+ )
118
199
 
119
- sdk_config = ABSmartlyConfig.create
120
- 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)
204
+
205
+ client_context_config = ContextConfig.create
206
+ client_context_config.set_unit('session_id', '5ebf06d8cb5d8137290c4abb64155584fbdb64d8')
121
207
 
122
- sdk = Absmartly.create(sdk_config)
208
+ client_context = sdk.create_context_with(client_context_config, server_context.data)
123
209
  ```
124
210
 
125
- **Refreshing the Context with Fresh Experiment Data**
211
+ ### Refreshing the Context with Fresh Experiment Data
126
212
 
127
- For long-running contexts, the context is usually created once when the
128
- application is first started. However, any experiments being tracked in your
129
- production code, but started after the context was created, will not be
130
- triggered.
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.
131
214
 
132
- Alternatively, the `refresh` method can be called manually. The
133
- `refresh` method pulls updated experiment data from the A/B
134
- Smartly collector and will trigger recently started experiments when
135
- `treatment` is called again.
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.
136
216
 
137
- **Setting Extra Units**
217
+ ```ruby
218
+ context.refresh
219
+ ```
220
+
221
+ ### Setting Extra Units
138
222
 
139
- You can add additional units to a context by calling the `set_unit()` or
140
- `set_units()` methods. These methods may be used, for example, when a user
141
- logs in to your application and you want to use the new unit type in the
142
- 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.
143
224
 
144
- Please note, you cannot override an already set unit type as that would be
145
- a change of identity and would throw an exception. In this case, you must
146
- create a new context instead. The `set_unit()` and
147
- `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.
148
226
 
149
227
  ```ruby
150
228
  context_config.set_unit('session_id', 'bf06d8cb5d8137290c4abb64155584fbdb64d8')
151
229
  context_config.set_unit('user_id', '123456')
152
230
  context = Absmartly.create_context(context_config)
153
231
  ```
154
- or
232
+
233
+ or
234
+
155
235
  ```ruby
156
236
  context_config.set_units(
157
237
  session_id: 'bf06d8cb5d8137290c4abb64155584fbdb64d8',
@@ -162,7 +242,7 @@ context = Absmartly.create_context(context_config)
162
242
 
163
243
  ## Basic Usage
164
244
 
165
- ### Selecting A Treatment
245
+ ### Selecting a Treatment
166
246
 
167
247
  ```ruby
168
248
  treatment = context.treatment('exp_test_experiment')
@@ -176,40 +256,41 @@ end
176
256
 
177
257
  ### Treatment Variables
178
258
 
179
- ```ruby
180
- default_button_color_value = 'red'
259
+ Variables allow you to configure experiment variants dynamically:
181
260
 
182
- 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)
183
264
  ```
184
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
+
185
270
  ### Peek at Treatment Variants
186
271
 
187
- Although generally not recommended, it is sometimes necessary to peek at
188
- a treatment or variable without triggering an exposure. The A/B Smartly
189
- 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.
190
273
 
191
274
  ```ruby
192
275
  treatment = context.peek_treatment('exp_test_experiment')
193
276
  ```
194
277
 
195
- #### Peeking at variables
278
+ #### Peeking at Variables
196
279
 
197
280
  ```ruby
198
- treatment = context.peek_variable_value('exp_test_experiment')
281
+ button_color = context.peek_variable_value('button.color', 'red')
199
282
  ```
200
283
 
201
284
  ### Overriding Treatment Variants
202
285
 
203
- During development, for example, it is useful to force a treatment for an
204
- experiment. This can be achieved with the `set_override()` and/or `set_overrides()`
205
- 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.
206
287
 
207
288
  ```ruby
208
- 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
209
290
 
210
291
  context.set_overrides(
211
- 'exp_test_experiment' => 1,
212
- 'exp_another_experiment' => 0,
292
+ 'exp_test_experiment' => 1,
293
+ 'exp_another_experiment' => 0
213
294
  )
214
295
  ```
215
296
 
@@ -217,70 +298,311 @@ context.set_overrides(
217
298
 
218
299
  ### Context Attributes
219
300
 
220
- Attributes are used to pass meta-data about the user and/or the request.
221
- They can be used later in the Web Console to create segments or audiences.
222
- They can be set using the `set_attribute()` or `set_attributes()`
223
- 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.
224
302
 
225
303
  ```ruby
226
- context.set_attribute('session_id', session_id)
304
+ context.set_attribute('user_agent', request.user_agent)
305
+
227
306
  context.set_attributes(
228
- 'customer_age' => 'new_customer'
307
+ customer_age: 'new_customer',
308
+ account_type: 'premium'
229
309
  )
230
310
  ```
231
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
+
232
335
  ### Custom Assignments
233
336
 
234
- Sometimes it may be necessary to override the automatic selection of a
235
- variant. For example, if you wish to have your variant chosen based on
236
- data from an API call. This can be accomplished using the
237
- `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.
238
338
 
239
339
  ```ruby
240
340
  chosen_variant = 1
241
341
  context.set_custom_assignment('experiment_name', chosen_variant)
242
342
  ```
243
343
 
244
- If you are running multiple experiments and need to choose different
245
- custom assignments for each one, you can do so using the
246
- `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.
247
345
 
248
346
  ```ruby
249
- assignments = [
250
- 'experiment_name' => 1,
251
- 'another_experiment_name' => 0,
252
- 'a_third_experiment_name' => 2
253
- ]
347
+ assignments = {
348
+ 'experiment_name' => 1,
349
+ 'another_experiment_name' => 0,
350
+ 'a_third_experiment_name' => 2
351
+ }
254
352
 
255
- context.set_custom_assignments(assignments)
353
+ context.set_custom_assignments(assignments)
256
354
  ```
257
355
 
258
- ### Publish
356
+ ### Tracking Goals
259
357
 
260
- Sometimes it is necessary to ensure all events have been published to the
261
- A/B Smartly collector, before proceeding. You can explicitly call the
262
- `publish()` methods.
358
+ Goals are created in the ABsmartly web console.
263
359
 
360
+ ```ruby
361
+ context.track('payment', {
362
+ item_count: 1,
363
+ total_amount: 1999.99
364
+ })
264
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
265
372
  context.publish
266
373
  ```
267
374
 
268
- ### Finalize
375
+ ### Finalizing
269
376
 
270
- The `close()` method will ensure all events have been
271
- published to the A/B Smartly collector, like `publish()`, and will also
272
- "seal" the context, throwing an error if any method that could generate
273
- 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.
274
378
 
275
- ```
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
276
382
  context.close
277
383
  ```
278
384
 
279
- ### 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.
280
400
 
281
401
  ```ruby
282
- context.track(
283
- 'payment',
284
- { 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
285
429
  )
286
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)