diff --git a/.gitignore b/.gitignore
index fded172..d9cc5c4 100644
--- a/.gitignore
+++ b/.gitignore
@@ -6,7 +6,7 @@
/vendor/bundle/
# macOS
-.DS_Store
+**/.DS_Store
# RSpec
/spec/examples.txt
@@ -19,3 +19,7 @@
.idea/
*.swp
*.swo
+
+.claude/
+AUDIT_REPORT.md
+FIXES_IMPLEMENTED.md
diff --git a/CHANGELOG.md b/CHANGELOG.md
new file mode 100644
index 0000000..ea360ef
--- /dev/null
+++ b/CHANGELOG.md
@@ -0,0 +1,52 @@
+# Changelog
+
+All notable changes to this project will be documented in this file.
+
+The format is based on [Keep a Changelog](https://keepachangelog.com/en/1.0.0/),
+and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0.html).
+
+## [Unreleased]
+
+### Security
+- Fixed XSS vulnerabilities in example templates by using proper JSON escaping
+- Removed API key exposure from client-side example templates
+- Added security documentation for safe template usage
+
+### Fixed
+- Removed thread-unsafe global state (`current_context`) to prevent cross-user data contamination
+- Added comprehensive exception handling throughout SDK to prevent page crashes
+- Added `ready?` checks consistently across all tags and filters
+- Fixed regex patterns to support experiment names with hyphens and dots
+- Fixed track filter to check `ready?` consistently with other filters
+- Fixed Drop methods to return results from track operations
+- Added input validation for all Drop methods
+- Fixed null reference errors in example templates
+
+### Added
+- Comprehensive logging throughout SDK with configurable logger
+- Strict mode option for fail-fast behavior in development/staging
+- Better error messages for syntax errors in tags
+- Warnings when context is missing or not ready
+- Warnings when tracking events are dropped
+
+### Changed
+- Removed global fallback in filters (now requires explicit Drop injection)
+- Improved property parsing in TrackTag to handle more complex values
+- Changed Drop to use `attr_reader` for cleaner code
+- Simplified filter implementations using `with_ready_context` helper
+
+### Removed
+- Removed `ABsmartly::Liquid.current_context` global variable (thread-unsafe)
+- Removed duplicate `liquid` dependency from Gemfile
+- Removed unused `rack-test` dependency from Gemfile
+- Removed `.DS_Store` files from repository
+
+## [1.0.0] - Initial Release
+
+### Added
+- Initial release of ABsmartly Liquid SDK
+- Support for Shopify Liquid templates
+- Filters for treatment assignment and variable resolution
+- Tags for treatment blocks and event tracking
+- Drop object for template integration
+- Example Shopify theme templates
diff --git a/Gemfile b/Gemfile
index dd71e7b..b1b6c93 100644
--- a/Gemfile
+++ b/Gemfile
@@ -2,11 +2,8 @@ source 'https://rubygems.org'
gemspec
-gem 'liquid', '~> 5.0'
-
group :development, :test do
gem 'rspec', '~> 3.12'
gem 'webmock', '~> 3.18'
- gem 'rack-test', '~> 2.0'
gem 'simplecov', '~> 0.22'
end
diff --git a/Gemfile.lock b/Gemfile.lock
index 91d7e0c..de274e6 100644
--- a/Gemfile.lock
+++ b/Gemfile.lock
@@ -40,9 +40,6 @@ GEM
net-http (0.9.1)
uri (>= 0.11.1)
public_suffix (7.0.2)
- rack (3.2.4)
- rack-test (2.2.0)
- rack (>= 1.3)
rake (13.3.1)
rexml (3.4.4)
rspec (3.13.2)
@@ -78,8 +75,6 @@ PLATFORMS
DEPENDENCIES
absmartly-liquid-sdk!
bundler (~> 2.0)
- liquid (~> 5.0)
- rack-test (~> 2.0)
rake (~> 13.0)
rspec (~> 3.12)
simplecov (~> 0.22)
diff --git a/LICENSE b/LICENSE
new file mode 100644
index 0000000..d6ea6a7
--- /dev/null
+++ b/LICENSE
@@ -0,0 +1,201 @@
+ Apache License
+ Version 2.0, January 2004
+ http://www.apache.org/licenses/
+
+ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
+
+ 1. Definitions.
+
+ "License" shall mean the terms and conditions for use, reproduction,
+ and distribution as defined by Sections 1 through 9 of this document.
+
+ "Licensor" shall mean the copyright owner or entity authorized by
+ the copyright owner that is granting the License.
+
+ "Legal Entity" shall mean the union of the acting entity and all
+ other entities that control, are controlled by, or are under common
+ control with that entity. For the purposes of this definition,
+ "control" means (i) the power, direct or indirect, to cause the
+ direction or management of such entity, whether by contract or
+ otherwise, or (ii) ownership of fifty percent (50%) or more of the
+ outstanding shares, or (iii) beneficial ownership of such entity.
+
+ "You" (or "Your") shall mean an individual or Legal Entity
+ exercising permissions granted by this License.
+
+ "Source" form shall mean the preferred form for making modifications,
+ including but not limited to software source code, documentation
+ source, and configuration files.
+
+ "Object" form shall mean any form resulting from mechanical
+ transformation or translation of a Source form, including but
+ not limited to compiled object code, generated documentation,
+ and conversions to other media types.
+
+ "Work" shall mean the work of authorship, whether in Source or
+ Object form, made available under the License, as indicated by a
+ copyright notice that is included in or attached to the work
+ (an example is provided in the Appendix below).
+
+ "Derivative Works" shall mean any work, whether in Source or Object
+ form, that is based on (or derived from) the Work and for which the
+ editorial revisions, annotations, elaborations, or other modifications
+ represent, as a whole, an original work of authorship. For the purposes
+ of this License, Derivative Works shall not include works that remain
+ separable from, or merely link (or bind by name) to the interfaces of,
+ the Work and Derivative Works thereof.
+
+ "Contribution" shall mean any work of authorship, including
+ the original version of the Work and any modifications or additions
+ to that Work or Derivative Works thereof, that is intentionally
+ submitted to Licensor for inclusion in the Work by the copyright owner
+ or by an individual or Legal Entity authorized to submit on behalf of
+ the copyright owner. For the purposes of this definition, "submitted"
+ means any form of electronic, verbal, or written communication sent
+ to the Licensor or its representatives, including but not limited to
+ communication on electronic mailing lists, source code control systems,
+ and issue tracking systems that are managed by, or on behalf of, the
+ Licensor for the purpose of discussing and improving the Work, but
+ excluding communication that is conspicuously marked or otherwise
+ designated in writing by the copyright owner as "Not a Contribution."
+
+ "Contributor" shall mean Licensor and any individual or Legal Entity
+ on behalf of whom a Contribution has been received by Licensor and
+ subsequently incorporated within the Work.
+
+ 2. Grant of Copyright License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ copyright license to reproduce, prepare Derivative Works of,
+ publicly display, publicly perform, sublicense, and distribute the
+ Work and such Derivative Works in Source or Object form.
+
+ 3. Grant of Patent License. Subject to the terms and conditions of
+ this License, each Contributor hereby grants to You a perpetual,
+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable
+ (except as stated in this section) patent license to make, have made,
+ use, offer to sell, sell, import, and otherwise transfer the Work,
+ where such license applies only to those patent claims licensable
+ by such Contributor that are necessarily infringed by their
+ Contribution(s) alone or by combination of their Contribution(s)
+ with the Work to which such Contribution(s) was submitted. If You
+ institute patent litigation against any entity (including a
+ cross-claim or counterclaim in a lawsuit) alleging that the Work
+ or a Contribution incorporated within the Work constitutes direct
+ or contributory patent infringement, then any patent licenses
+ granted to You under this License for that Work shall terminate
+ as of the date such litigation is filed.
+
+ 4. Redistribution. You may reproduce and distribute copies of the
+ Work or Derivative Works thereof in any medium, with or without
+ modifications, and in Source or Object form, provided that You
+ meet the following conditions:
+
+ (a) You must give any other recipients of the Work or
+ Derivative Works a copy of this License; and
+
+ (b) You must cause any modified files to carry prominent notices
+ stating that You changed the files; and
+
+ (c) You must retain, in the Source form of any Derivative Works
+ that You distribute, all copyright, patent, trademark, and
+ attribution notices from the Source form of the Work,
+ excluding those notices that do not pertain to any part of
+ the Derivative Works; and
+
+ (d) If the Work includes a "NOTICE" text file as part of its
+ distribution, then any Derivative Works that You distribute must
+ include a readable copy of the attribution notices contained
+ within such NOTICE file, excluding those notices that do not
+ pertain to any part of the Derivative Works, in at least one
+ of the following places: within a NOTICE text file distributed
+ as part of the Derivative Works; within the Source form or
+ documentation, if provided along with the Derivative Works; or,
+ within a display generated by the Derivative Works, if and
+ wherever such third-party notices normally appear. The contents
+ of the NOTICE file are for informational purposes only and
+ do not modify the License. You may add Your own attribution
+ notices within Derivative Works that You distribute, alongside
+ or as an addendum to the NOTICE text from the Work, provided
+ that such additional attribution notices cannot be construed
+ as modifying the License.
+
+ You may add Your own copyright statement to Your modifications and
+ may provide additional or different license terms and conditions
+ for use, reproduction, or distribution of Your modifications, or
+ for any such Derivative Works as a whole, provided Your use,
+ reproduction, and distribution of the Work otherwise complies with
+ the conditions stated in this License.
+
+ 5. Submission of Contributions. Unless You explicitly state otherwise,
+ any Contribution intentionally submitted for inclusion in the Work
+ by You to the Licensor shall be under the terms and conditions of
+ this License, without any additional terms or conditions.
+ Notwithstanding the above, nothing herein shall supersede or modify
+ the terms of any separate license agreement you may have executed
+ with Licensor regarding such Contributions.
+
+ 6. Trademarks. This License does not grant permission to use the trade
+ names, trademarks, service marks, or product names of the Licensor,
+ except as required for reasonable and customary use in describing the
+ origin of the Work and reproducing the content of the NOTICE file.
+
+ 7. Disclaimer of Warranty. Unless required by applicable law or
+ agreed to in writing, Licensor provides the Work (and each
+ Contributor provides its Contributions) on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
+ implied, including, without limitation, any warranties or conditions
+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
+ PARTICULAR PURPOSE. You are solely responsible for determining the
+ appropriateness of using or redistributing the Work and assume any
+ risks associated with Your exercise of permissions under this License.
+
+ 8. Limitation of Liability. In no event and under no legal theory,
+ whether in tort (including negligence), contract, or otherwise,
+ unless required by applicable law (such as deliberate and grossly
+ negligent acts) or agreed to in writing, shall any Contributor be
+ liable to You for damages, including any direct, indirect, special,
+ incidental, or consequential damages of any character arising as a
+ result of this License or out of the use or inability to use the
+ Work (including but not limited to damages for loss of goodwill,
+ work stoppage, computer failure or malfunction, or any and all
+ other commercial damages or losses), even if such Contributor
+ has been advised of the possibility of such damages.
+
+ 9. Accepting Warranty or Additional Support. While redistributing
+ the Work or Derivative Works thereof, You may choose to offer,
+ and charge a fee for, acceptance of support, warranty, indemnity,
+ or other liability obligations and/or rights consistent with this
+ License. However, in accepting such obligations, You may act only
+ on Your own behalf and on Your sole responsibility, not on behalf
+ of any other Contributor, and only if You agree to indemnify,
+ defend, and hold each Contributor harmless for any liability
+ incurred by, or claims asserted against, such Contributor by reason
+ of your accepting any such warranty or additional liability.
+
+ END OF TERMS AND CONDITIONS
+
+ APPENDIX: How to apply the Apache License to your work.
+
+ To apply the Apache License to your work, attach the following
+ boilerplate notice, with the fields enclosed by brackets "[]"
+ replaced with your own identifying information. (Don't include
+ the brackets!) The text should be enclosed in the appropriate
+ comment syntax for the file format. We also recommend that a
+ file or class name and description of purpose be included on the
+ same "printed page" as the copyright notice for easier
+ identification within third-party archives.
+
+ Copyright 2024 ABsmartly
+
+ Licensed under the Apache License, Version 2.0 (the "License");
+ you may not use this file except in compliance with the License.
+ You may obtain a copy of the License at
+
+ http://www.apache.org/licenses/LICENSE-2.0
+
+ Unless required by applicable law or agreed to in writing, software
+ distributed under the License is distributed on an "AS IS" BASIS,
+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
+ See the License for the specific language governing permissions and
+ limitations under the License.
diff --git a/README.md b/README.md
index 3fdd870..390e0e3 100644
--- a/README.md
+++ b/README.md
@@ -1,49 +1,21 @@
-# ABsmartly SDK for Shopify Liquid
+# ABsmartly Liquid SDK
-A/B Smartly SDK for Shopify Liquid templating language with server-side rendering support.
-
-## Overview
-
-This SDK enables A/B testing in Shopify stores using Liquid templates. It provides Liquid filters, tags, and drops (objects) that integrate with ABsmartly's experimentation platform.
-
-**Architecture:**
-- Ruby backend SDK (handles HTTP, variant assignment, hashing)
-- Liquid filters and tags for template integration
-- Server-side context initialization and caching
-- Shopify theme integration
+A/B testing SDK for [Shopify Liquid](https://shopify.github.io/liquid/) templating language and [Jekyll](https://jekyllrb.com/) static site generator. This SDK brings the power of ABsmartly's experimentation platform to server-side rendered templates.
## Compatibility
-- Shopify Liquid templates
-- Ruby 2.7+ (Shopify backend)
-- Works with Shopify themes and apps
-
-## Installation
-
-### For Shopify Themes
-
-1. Add the ABsmartly Liquid SDK files to your theme:
+The ABsmartly Liquid SDK is compatible with:
-```
-assets/
- absmartly.js # Client-side tracking (optional)
-snippets/
- absmartly-init.liquid # Initialization snippet
- absmartly-tracking.liquid # Tracking snippet
-```
+- **Ruby**: Version 3.0 and later
+- **Liquid**: Version 5.0 and later
+- **Shopify Themes**: All modern Shopify themes
+- **Jekyll**: Version 4.0 and later
-2. Add initialization to your `theme.liquid`:
+**Note on Naming:** This SDK uses the module name `ABsmartly::Liquid` (with namespace) to avoid clashing with the Ruby SDK's main module (`Absmartly`). When requiring the gem, use `require 'absmartly/liquid'`.
-```liquid
-{% render 'absmartly-init',
- session_id: customer.id | default: request.cookie.session_id,
- customer_id: customer.id
-%}
-```
-
-### For Shopify Apps
+## Installation
-Add to your Gemfile:
+Add to your `Gemfile`:
```ruby
gem 'absmartly-liquid-sdk'
@@ -55,586 +27,420 @@ Then run:
bundle install
```
-## Quick Start
-
-### 1. Initialize Context (Server-Side)
-
-In your Shopify app controller or theme:
-
-```ruby
-# Initialize SDK
-sdk = ABSmartly::SDK.new(
- endpoint: 'https://your-endpoint.absmartly.io/v1',
- api_key: ENV['ABSMARTLY_API_KEY'],
- application: 'shopify-store',
- environment: 'production'
-)
-
-# Create context
-@absmartly_context = sdk.create_context(
- units: {
- session_id: session[:id],
- customer_id: current_customer&.id
- }
-)
-
-# Wait for ready
-@absmartly_context.ready
+For Jekyll sites, also add to your `_config.yml`:
-# Make context available to Liquid
-@absmartly_data = {
- 'context_data' => @absmartly_context.data.to_json,
- 'units' => @absmartly_context.get_units
-}
+```yaml
+plugins:
+ - absmartly-liquid-sdk
```
-### 2. Use in Liquid Templates
-
-#### Treatment Assignment
-
-```liquid
-{% assign variant = 'exp_button_color' | absmartly_treatment %}
-
-{% if variant == 0 %}
-
-{% elsif variant == 1 %}
-
-{% endif %}
-```
+## Getting Started
-#### Variable Access
+Please follow the [installation](#installation) instructions before trying the following code.
-```liquid
-{% assign button_text = 'button_text' | absmartly_variable: 'Buy Now' %}
-
-```
+### Initialization
-#### Peek (Without Tracking)
+This example assumes an API Key, an Application, and an Environment have been created in the ABsmartly web console.
-```liquid
-{% assign variant = 'exp_button_color' | absmartly_peek %}
-```
-
-#### Goal Tracking
+```ruby
+require 'absmartly/liquid'
-```liquid
-{% absmartly_track 'add_to_cart', amount: product.price, quantity: 1 %}
+sdk = ABSmartly::SDK.new(
+ endpoint: 'https://your-company.absmartly.io/v1',
+ api_key: ENV['ABSMARTLY_API_KEY'],
+ application: 'my-shopify-store',
+ environment: 'production'
+)
```
-Or use the filter:
+#### With Optional Parameters
-```liquid
-{{ 'purchase' | absmartly_track: amount: order.total_price }}
+```ruby
+sdk = ABSmartly::SDK.new(
+ endpoint: 'https://your-company.absmartly.io/v1',
+ api_key: ENV['ABSMARTLY_API_KEY'],
+ application: 'my-shopify-store',
+ environment: 'production',
+ retries: 3,
+ timeout: 5000
+)
```
-### 3. Client-Side Tracking (Optional)
+**SDK Options**
-For tracking after page load:
+| Option | Type | Required? | Default | Description |
+| :----------- | :-------- | :-------: | :-----: | :---------------------------------------------------------------------------------------------------------------------------------------------------------------------------- |
+| endpoint | `String` | ✅ | `nil` | The URL to your API endpoint. Most commonly `"https://your-company.absmartly.io/v1"` |
+| api_key | `String` | ✅ | `nil` | Your API key which can be found on the Web Console. |
+| environment | `String` | ✅ | `nil` | The environment of the platform where the SDK is installed. Environments are created on the Web Console. |
+| application | `String` | ✅ | `nil` | The name of the application where the SDK is installed. Applications are created on the Web Console. |
+| retries | `Integer` | ❌ | `5` | Maximum number of HTTP retries for failed requests |
+| timeout | `Integer` | ❌ | `3000` | HTTP timeout in milliseconds |
+| event_logger | `Proc` | ❌ | `nil` | Custom event logger callback (see Advanced section) |
-```liquid
-
-```
+## Creating a New Context
-## Liquid Filters
+### Synchronously
-### `absmartly_treatment`
+```ruby
+context = sdk.create_context(
+ units: {
+ session_id: session[:id],
+ customer_id: current_customer&.id
+ }
+)
-Get variant and track exposure.
+context.ready
-```liquid
-{% assign variant = 'exp_test' | absmartly_treatment %}
+drop = ABSmartly::Liquid::Drop.new(context)
```
-**Returns:** Variant number (0, 1, 2, ...)
+### With Pre-fetched Data
-**Side effect:** Tracks exposure event
+For better performance, pre-fetch context data and reuse it to avoid an additional round-trip.
-### `absmartly_peek`
+```ruby
+data = sdk.get_client.get_context(
+ units: { session_id: session[:id] }
+)
-Get variant without tracking exposure.
+context = sdk.create_context_with(
+ { units: { session_id: session[:id] } },
+ data
+)
-```liquid
-{% assign variant = 'exp_test' | absmartly_peek %}
+drop = ABSmartly::Liquid::Drop.new(context)
```
-**Returns:** Variant number (0, 1, 2, ...)
-
-**Side effect:** None
+### Refreshing the Context with Fresh Experiment Data
-### `absmartly_variable`
+For long-running contexts, the context is usually created once when the application is first started. However, any experiments started after the context was created will not be triggered.
-Get variable value and track exposure.
+```ruby
+context = sdk.create_context(
+ units: { session_id: session[:id] },
+ refresh_period: 4 * 60 * 60 * 1000
+)
-```liquid
-{% assign value = 'button_color' | absmartly_variable: 'blue' %}
+# Or refresh manually
+context.refresh
```
-**Parameters:**
-- First argument (pipe input): Variable key
-- Second argument: Default value
+### Setting Extra Units
-**Returns:** Variable value or default
+You can add additional units to a context. This may be used, for example, when a user logs in to your application.
-**Side effect:** Tracks exposure event
+**Note:** You cannot override an already set unit type as that would be a change of identity. In this case, you must create a new context instead.
-### `absmartly_peek_variable`
-
-Get variable value without tracking exposure.
-
-```liquid
-{% assign value = 'button_color' | absmartly_peek_variable: 'blue' %}
+```ruby
+context.set_unit('db_user_id', '1000013')
```
-**Returns:** Variable value or default
-
-**Side effect:** None
+## Basic Usage
-### `absmartly_track`
+### Treatment Selection with Filters
-Track goal achievement.
+Use the `absmartly_treatment` filter to select a treatment variant:
```liquid
-{{ 'purchase' | absmartly_track: amount: order.total_price, items: order.line_items.size }}
-```
-
-**Parameters:**
-- First argument (pipe input): Goal name
-- Named parameters: Goal properties (must be numeric)
-
-**Returns:** Empty string
-
-**Side effect:** Queues goal event for publishing
-
-### `absmartly_custom_field`
-
-Get custom field value.
+{% assign variant = 'exp_button_color' | absmartly_treatment %}
-```liquid
-{% assign metadata = 'exp_test' | absmartly_custom_field: 'metadata' %}
+{% if variant == 0 %}
+
+{% elsif variant == 1 %}
+
+{% endif %}
```
-**Returns:** Parsed field value based on type
-
-## Liquid Tags
+### Treatment Selection with Block Tag
-### `absmartly_treatment`
-
-Block tag for treatment assignment.
+Use the block tag for cleaner syntax with a local `variant` variable:
```liquid
{% absmartly_treatment 'exp_button_color' %}
{% if variant == 0 %}
-
+
{% elsif variant == 1 %}
-
+
{% endif %}
{% endabsmartly_treatment %}
```
-Inside the block, `variant` variable is available.
-
-### `absmartly_track`
+### Treatment Variables
-Track goal with properties.
+Variables allow you to configure experiment variations without code changes:
```liquid
-{% absmartly_track 'purchase', amount: order.total_price, items: order.line_items.size %}
+{% assign button_text = 'checkout_button_text' | absmartly_variable: 'Checkout' %}
+{% assign button_color = 'checkout_button_color' | absmartly_variable: 'blue' %}
+
+
+ {{ button_text }}
+
```
-## Liquid Drops (Objects)
+### Peek at Treatment Variants
-ABsmartly context is available as `absmartly` object in Liquid:
+Although generally not recommended, it is sometimes necessary to peek at a treatment without triggering an exposure.
```liquid
-{{ absmartly.experiments }}
-{{ absmartly.pending }}
-{{ absmartly.ready }}
+{% assign variant = 'exp_feature' | absmartly_peek %}
```
-### Properties
-
-- `ready` (boolean) - Whether context is ready
-- `failed` (boolean) - Whether context failed to load
-- `finalized` (boolean) - Whether context is finalized
-- `experiments` (array) - List of experiment names
-- `pending` (number) - Count of pending events
-
-### Methods
+#### Peeking at Variables
```liquid
-{{ absmartly.treatment('exp_test') }}
-{{ absmartly.peek('exp_test') }}
-{{ absmartly.variable('button_color', 'blue') }}
-{{ absmartly.peek_variable('button_color', 'blue') }}
-{{ absmartly.custom_field('exp_test', 'metadata') }}
-{{ absmartly.track('goal_name', properties) }}
+{% assign color = 'button_color' | absmartly_peek_variable: 'blue' %}
```
-## Server-Side Integration
+### Overriding Treatment Variants
-### Shopify App Example
+During development, force specific variants:
```ruby
-class ProductsController < ApplicationController
- before_action :init_absmartly
-
- def show
- @product = Product.find(params[:id])
-
- # Get variant for this user
- variant = @absmartly.treatment('exp_product_layout')
-
- # Pass to view
- @layout_variant = variant
+context.override('exp_test', 1)
- # Data for Liquid
- @absmartly_liquid = ABSmartly::LiquidDrop.new(@absmartly)
- end
-
- private
-
- def init_absmartly
- @absmartly = $absmartly_sdk.create_context(
- units: {
- session_id: session[:id],
- customer_id: current_customer&.id
- }
- )
- @absmartly.ready
- end
-end
+context.overrides({
+ 'exp_test' => 1,
+ 'exp_another' => 0
+})
```
-### Theme Liquid Integration
+### Tracking Goals
+
+Track goal achievement with properties:
```liquid
-
-{% capture session_id %}{{ request.cookie['_shopify_s'] }}{% endcapture %}
-
-{% render 'absmartly-init',
- endpoint: 'https://your-endpoint.absmartly.io/v1',
- api_key: 'your-api-key',
- session_id: session_id,
- customer_id: customer.id
-%}
-
-
-{% assign layout_variant = 'exp_product_layout' | absmartly_treatment %}
-
-{% if layout_variant == 0 %}
- {% render 'product-layout-control' %}
-{% elsif layout_variant == 1 %}
- {% render 'product-layout-treatment' %}
-{% endif %}
+
+{{ 'purchase' | absmartly_track: amount: order.total_price, items: order.line_items.size }}
+
+
+{% absmartly_track 'add_to_cart', product_id: product.id, price: product.price %}
```
-## Advanced Usage
+## Advanced
-### Pre-fetching Context Data
+### Context Attributes
-For better performance, pre-fetch context data server-side:
+Add metadata for audience targeting:
```ruby
-# In controller
-data = sdk.get_client.get_context(units: { session_id: session[:id] })
+context.attributes({
+ user_agent: request.user_agent,
+ customer_age: 'new_customer',
+ account_type: 'premium'
+})
+```
-# Create context with data (no HTTP call)
-@absmartly = sdk.create_context_with(
- { units: { session_id: session[:id] } },
- data
-)
+### Publishing Pending Data
+
+Ensure all events are published before proceeding:
-# Pass to Liquid
-assigns['absmartly'] = ABSmartly::LiquidDrop.new(@absmartly)
+```ruby
+context.publish
```
-### Caching Context Data
+### Finalizing
-```ruby
-# Cache context data for session
-cache_key = "absmartly:#{session[:id]}"
-data = Rails.cache.fetch(cache_key, expires_in: 5.minutes) do
- sdk.get_client.get_context(units: { session_id: session[:id] })
-end
+The `close` method will ensure all events have been published to the ABsmartly collector, like `publish`, and will also "seal" the context, preventing any further events from being tracked.
-@absmartly = sdk.create_context_with({ units: { session_id: session[:id] } }, data)
+```ruby
+context.close
```
### Custom Event Logger
+Monitor SDK events for debugging, analytics, or integrating with other systems.
+
```ruby
-class ShopifyEventLogger
- def handle_event(context, event_name, data)
- case event_name
- when 'exposure'
- # Log to Shopify analytics
- Analytics.track('absmartly_exposure', data)
- when 'goal'
- # Log to your tracking system
- Tracking.event('absmartly_goal', data)
- when 'error'
- # Log errors
- Rails.logger.error("ABsmartly error: #{data}")
- end
+event_logger = ->(context, event_name, data) {
+ case event_name
+ when 'exposure'
+ Rails.logger.info "ABsmartly exposure: #{data[:name]}"
+ when 'goal'
+ Rails.logger.info "ABsmartly goal: #{data[:name]}"
+ when 'error'
+ Rails.logger.error "ABsmartly error: #{data}"
+ when 'ready'
+ Rails.logger.info "ABsmartly context ready"
+ when 'refresh'
+ Rails.logger.info "ABsmartly context refreshed"
+ when 'publish'
+ Rails.logger.info "ABsmartly events published"
+ when 'close'
+ Rails.logger.info "ABsmartly context closed"
end
-end
+}
sdk = ABSmartly::SDK.new(
endpoint: ENV['ABSMARTLY_ENDPOINT'],
api_key: ENV['ABSMARTLY_API_KEY'],
- application: 'shopify-store',
+ application: 'my-store',
environment: Rails.env,
- event_logger: ShopifyEventLogger.new
+ event_logger: event_logger
)
```
-### Publishing Events
+**Event Types**
-Events are automatically published, but you can manually publish:
+| Event | When | Data |
+| :--------- | :------------------------------------------- | :----------------------------------- |
+| `ready` | Context turns ready | Context initialization data |
+| `refresh` | `refresh()` succeeds | Refreshed context data |
+| `publish` | `publish()` succeeds | Published events |
+| `exposure` | `treatment()` succeeds on first exposure | Exposure data |
+| `goal` | `track()` succeeds | Goal data |
+| `close` | `close()` succeeds the first time | `nil` |
+| `error` | Error occurs | Error object |
-```ruby
-# In controller after action
-@absmartly.publish
-```
-
-Or finalize on session end:
-
-```ruby
-# In ApplicationController
-after_action :finalize_absmartly
-
-def finalize_absmartly
- @absmartly&.finalize
-end
-```
+## Liquid API Reference
-## Examples
+### Filters
-### Product Page A/B Test
+| Filter | Description | Returns |
+| :------------------------ | :---------------------------------------------- | :------------------------------- |
+| `absmartly_treatment` | Get treatment variant and track exposure | Integer variant number (0, 1, ...) |
+| `absmartly_peek` | Get treatment variant without tracking exposure | Integer variant number |
+| `absmartly_variable` | Get variable value and track exposure | Variable value or default |
+| `absmartly_peek_variable` | Get variable value without tracking exposure | Variable value or default |
+| `absmartly_custom_field` | Get custom field value for an experiment | Parsed field value |
+| `absmartly_track` | Track goal achievement with properties | Empty string |
-```liquid
-
-{% assign variant = 'exp_product_images' | absmartly_treatment %}
+### Tags
-{% if variant == 0 %}
-
-
-{% elsif variant == 1 %}
-
-
- {% for image in product.images %}
-
- {% endfor %}
-
-{% endif %}
+| Tag | Description |
+| :---------------------------- | :---------------------------------------------- |
+| `{% absmartly_treatment %}` | Block tag for treatment with local `variant` variable |
+| `{% absmartly_track %}` | Tag for tracking goals with properties |
-
-
-```
+### Drop Object
-### Checkout Button Text
+The `absmartly` drop object is available in templates when injected via `ABSmartly::Liquid::Drop.new(context)`:
```liquid
-{% assign button_text = 'checkout_button_text' | absmartly_variable: 'Checkout' %}
-{% assign button_color = 'checkout_button_color' | absmartly_variable: 'blue' %}
-
-
- {{ button_text }}
-
-```
-
-### Free Shipping Threshold
-
-```liquid
-{% assign free_shipping_threshold = 'free_shipping_threshold' | absmartly_variable: 50 %}
-
-{% if cart.total_price >= free_shipping_threshold %}
-