laboratory 0.1.0

Sign up to get free protection for your applications and to get access to all the features.
checksums.yaml ADDED
@@ -0,0 +1,7 @@
1
+ ---
2
+ SHA256:
3
+ metadata.gz: fddd4e5310fe374f6dce5c3662d4e171987a3aa1cd180fca0f4123890c74ff74
4
+ data.tar.gz: 22957e0e5595b93d4005dac1329f87ccc78428576a1b4519e7634edcb405eac3
5
+ SHA512:
6
+ metadata.gz: 9ed204a1530ce008417f27407188a102982d77ec175f62fd0f117b9035c8f091f08700572798f9071ac2c352e5f199e8e6a53f114864005622e054beb69073a6
7
+ data.tar.gz: b0fbec760e8b1187ed5917b4d9e7ddd936e9b7caebc2f89738ed4d09fe6688a9343394eb2fac7e18f13b6ef0821226f6cfc4d4e6be39ccf3d4e12afe628dfdfd
data/.gitignore ADDED
@@ -0,0 +1,11 @@
1
+ /.bundle/
2
+ /.yardoc
3
+ /_yardoc/
4
+ /coverage/
5
+ /doc/
6
+ /pkg/
7
+ /spec/reports/
8
+ /tmp/
9
+
10
+ # rspec failure tracking
11
+ .rspec_status
data/.rspec ADDED
@@ -0,0 +1,3 @@
1
+ --format documentation
2
+ --color
3
+ --require spec_helper
data/.travis.yml ADDED
@@ -0,0 +1,6 @@
1
+ ---
2
+ language: ruby
3
+ cache: bundler
4
+ rvm:
5
+ - 2.6.0
6
+ before_install: gem install bundler -v 2.1.4
@@ -0,0 +1,74 @@
1
+ # Contributor Covenant Code of Conduct
2
+
3
+ ## Our Pledge
4
+
5
+ In the interest of fostering an open and welcoming environment, we as
6
+ contributors and maintainers pledge to making participation in our project and
7
+ our community a harassment-free experience for everyone, regardless of age, body
8
+ size, disability, ethnicity, gender identity and expression, level of experience,
9
+ nationality, personal appearance, race, religion, or sexual identity and
10
+ orientation.
11
+
12
+ ## Our Standards
13
+
14
+ Examples of behavior that contributes to creating a positive environment
15
+ include:
16
+
17
+ * Using welcoming and inclusive language
18
+ * Being respectful of differing viewpoints and experiences
19
+ * Gracefully accepting constructive criticism
20
+ * Focusing on what is best for the community
21
+ * Showing empathy towards other community members
22
+
23
+ Examples of unacceptable behavior by participants include:
24
+
25
+ * The use of sexualized language or imagery and unwelcome sexual attention or
26
+ advances
27
+ * Trolling, insulting/derogatory comments, and personal or political attacks
28
+ * Public or private harassment
29
+ * Publishing others' private information, such as a physical or electronic
30
+ address, without explicit permission
31
+ * Other conduct which could reasonably be considered inappropriate in a
32
+ professional setting
33
+
34
+ ## Our Responsibilities
35
+
36
+ Project maintainers are responsible for clarifying the standards of acceptable
37
+ behavior and are expected to take appropriate and fair corrective action in
38
+ response to any instances of unacceptable behavior.
39
+
40
+ Project maintainers have the right and responsibility to remove, edit, or
41
+ reject comments, commits, code, wiki edits, issues, and other contributions
42
+ that are not aligned to this Code of Conduct, or to ban temporarily or
43
+ permanently any contributor for other behaviors that they deem inappropriate,
44
+ threatening, offensive, or harmful.
45
+
46
+ ## Scope
47
+
48
+ This Code of Conduct applies both within project spaces and in public spaces
49
+ when an individual is representing the project or its community. Examples of
50
+ representing a project or community include using an official project e-mail
51
+ address, posting via an official social media account, or acting as an appointed
52
+ representative at an online or offline event. Representation of a project may be
53
+ further defined and clarified by project maintainers.
54
+
55
+ ## Enforcement
56
+
57
+ Instances of abusive, harassing, or otherwise unacceptable behavior may be
58
+ reported by contacting the project team at npaters@tcd.ie. All
59
+ complaints will be reviewed and investigated and will result in a response that
60
+ is deemed necessary and appropriate to the circumstances. The project team is
61
+ obligated to maintain confidentiality with regard to the reporter of an incident.
62
+ Further details of specific enforcement policies may be posted separately.
63
+
64
+ Project maintainers who do not follow or enforce the Code of Conduct in good
65
+ faith may face temporary or permanent repercussions as determined by other
66
+ members of the project's leadership.
67
+
68
+ ## Attribution
69
+
70
+ This Code of Conduct is adapted from the [Contributor Covenant][homepage], version 1.4,
71
+ available at [https://contributor-covenant.org/version/1/4][version]
72
+
73
+ [homepage]: https://contributor-covenant.org
74
+ [version]: https://contributor-covenant.org/version/1/4/
data/Gemfile ADDED
@@ -0,0 +1,6 @@
1
+ source "https://rubygems.org"
2
+
3
+ # Specify your gem's dependencies in laboratory.gemspec
4
+ gemspec
5
+
6
+ gem "rake", "~> 12.0"
data/Gemfile.lock ADDED
@@ -0,0 +1,39 @@
1
+ PATH
2
+ remote: .
3
+ specs:
4
+ laboratory (0.1.0)
5
+ redis (>= 2.1)
6
+
7
+ GEM
8
+ remote: https://rubygems.org/
9
+ specs:
10
+ diff-lcs (1.3)
11
+ fakeredis (0.8.0)
12
+ redis (~> 4.1)
13
+ rake (12.3.3)
14
+ redis (4.1.3)
15
+ rspec (3.9.0)
16
+ rspec-core (~> 3.9.0)
17
+ rspec-expectations (~> 3.9.0)
18
+ rspec-mocks (~> 3.9.0)
19
+ rspec-core (3.9.1)
20
+ rspec-support (~> 3.9.1)
21
+ rspec-expectations (3.9.1)
22
+ diff-lcs (>= 1.2.0, < 2.0)
23
+ rspec-support (~> 3.9.0)
24
+ rspec-mocks (3.9.1)
25
+ diff-lcs (>= 1.2.0, < 2.0)
26
+ rspec-support (~> 3.9.0)
27
+ rspec-support (3.9.2)
28
+
29
+ PLATFORMS
30
+ ruby
31
+
32
+ DEPENDENCIES
33
+ fakeredis (~> 0.8)
34
+ laboratory!
35
+ rake (~> 12.0)
36
+ rspec (~> 3.8)
37
+
38
+ BUNDLED WITH
39
+ 2.1.4
data/LICENSE.txt ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License (MIT)
2
+
3
+ Copyright (c) 2020 Niall Paterson
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
data/README.md ADDED
@@ -0,0 +1,265 @@
1
+ # Laboratory 🧪
2
+
3
+ Laboratory is an A/B testing and Feature Flag framework for Rails. It's focused on a number of key philosophies, all garnered from running A/B tests and feature flags in commercial settings and experiencing issues with other A/B testing gems out there:
4
+
5
+ * Cohesiveness
6
+ * A/B tests and feature flags are, in many ways, very similar. Laboratory looks to marry them into a single 'Experiment' concept.
7
+ * Flexiblity
8
+ * Laboratory allows you manage your A/B tests and feature flags with no code changes, through the Laboratory UI.
9
+ * Tracability and Accountability
10
+ * It is vital that any updates or changes to an A/B test or feature flag is documented in a changelog with full tracability back to the user who performed the change. This is built into Laboratory.
11
+ * Simplicity, while not being simplisitic
12
+ * Laboratory comes with a single A/B test algorithm and single storage adapter built-in, which we think will cover 99% of use cases for A/B testing and Feature Flagging. If you're in that 1%, it's easy to extend Laboratory to add custom Algorithms and Storage mechanisms.
13
+
14
+ ## Installation
15
+
16
+ Add this line to your application's Gemfile:
17
+
18
+ ```ruby
19
+ gem 'laboratory'
20
+ ```
21
+
22
+ And then execute:
23
+
24
+ $ bundle install
25
+
26
+ Or install it yourself as:
27
+
28
+ $ gem install laboratory
29
+
30
+
31
+ ## Usage
32
+
33
+ ### Defining the adapter
34
+
35
+ In an initializer (`app/config/initializers/laboratory.rb`), define the adapter you are going to use with Laboratory. Laboratory supports Redis out of the box, as it the recommended adapter:
36
+
37
+ ```ruby
38
+ Laboratory::Config.adapter = Laboratory::Adapters::RedisAdapter.new(url: 'redis://localhost:6789') # Adjust to your redis URL.
39
+ ```
40
+
41
+ ### Defining your current_user_id & actor
42
+
43
+ Laboratory needs to know which user is currently active when determining which variant to use for an experiment. It is also useful to define an 'actor' - the user who actions any changes to any Laboratory experiments - for better accountability and tracability tracking through the changelog.
44
+
45
+ For **Rails**, we recommend defining a before_action in application_controller to do this:
46
+
47
+ ```ruby
48
+ class ApplicationController
49
+
50
+ before_action :set_laboratory_current_user_id
51
+ before_action :set_laboratory_actor
52
+
53
+ def set_laboratory_current_user_id
54
+ Laboratory::Config.current_user_id = your_current_user_id
55
+ end
56
+
57
+ def set_laboratory_actor
58
+ Laboratory::Config.actor = 'Tom Jones'
59
+ end
60
+ ```
61
+
62
+ Note: From experience, we recommend storing an identifier in a cookie once a new device is identified, and storing it on the user once that user has been identified (by signing up, logging in etc). This identifier should not change when the user logs out as otherwise you will find users experiencing multiple variants of the same test.
63
+
64
+
65
+ ### Setting up an experiment
66
+
67
+ We recommend defining all of your A/B tests and feature flags in a single location (like an initializer) to make it easy to keep track of all tests and flags running but it absolutely possible to define them wherever they are needed. We use `find_or_create` below to create them to ensure they are created the first time they are deployed, and maintained throughout:
68
+
69
+ ```ruby
70
+ Laboratory::Experiment.find_or_create(
71
+ id: 'blue_button_ab_test',
72
+ variants: [
73
+ {
74
+ id: 'control',
75
+ percentage: 50 # Note these percentages are just the initial starting percentages and may be adjusted dynamically in the future.
76
+ },
77
+ {
78
+ id: 'variant_a',
79
+ percentage: 50
80
+ }
81
+ ]
82
+ )
83
+
84
+ Laboratory::Experiment.find_or_create(
85
+ id: 'new_checkout_feature_flag',
86
+ variants: [
87
+ {
88
+ id: 'control',
89
+ percentage: 100
90
+ },
91
+ {
92
+ id: 'new_checkout',
93
+ percentage: 0
94
+ }
95
+ ]
96
+ )
97
+ ```
98
+
99
+ ### Using an experiment
100
+
101
+ Once an experiment has been defined, it's simple to use the experiment:
102
+
103
+ ```ruby
104
+ experiment = Laboratory::Experiment.find('blue_button_ab_test')
105
+ variant = experiment.variant
106
+
107
+ if variant.id == 'control'
108
+ ...
109
+ else
110
+ ...
111
+ end
112
+ ```
113
+
114
+ Note the `#variant` method also takes an optional user parameter should you want to define the user specifically in this case. It defaults to a user with the current_user_id defined in the Laboratory configuration.
115
+
116
+ ### Defining an event
117
+
118
+ Events are a way to track key milestones for the purposes of later analysis. Each event is then displayed on the Laboratory Dashboard with significance levels. An event can be recorded as follows:
119
+
120
+ ```ruby
121
+ experiment = Laboratory::Experiment.find('blue_button_ab_test')
122
+ experiment.record_event!('completed')
123
+ ```
124
+
125
+ Note the `#record_event!` method also takes an optional user parameter should you want to define the user specifically in this case. It defaults to a user with the current_user_id defined in the Laboratory configuration.
126
+
127
+ ### Using the Laboratory UI
128
+
129
+ It's easy to analyse and manage your experiment from the dashboard. In routes.rb, mount the dashboard behind your appropriate authentication layer (this example uses Devise):
130
+
131
+ ```ruby
132
+ authenticate :admin_user do
133
+ mount Laboratory::UI, at: 'admin/laboratory'
134
+ ...
135
+ end
136
+ ```
137
+
138
+ You can now visit /admin/laboratory to view the progess of your experiment, and update the variants as needed.
139
+
140
+ ### Analytics Integrations
141
+
142
+ It's common to trigger analytics events upon common actions like a user being assigned to a variant, or an event occuring. Laboratory makes it easy to do this through two callback handlers that can be defined as so:
143
+
144
+ **When a user gets assigned to a variant**:
145
+
146
+ ```ruby
147
+ Laboratory::Config.on_assignment_to_variant = -> (experiment, variant, user) {
148
+ ...
149
+ }
150
+ ```
151
+
152
+ **When an event is recorded**:
153
+
154
+ ```ruby
155
+ Laboratory::Config.on_event_recorded = -> (experiment, variant, user, event) {
156
+ ...
157
+ }
158
+ ```
159
+
160
+ ### Managing an Experiment outside the regular request cycle
161
+
162
+ Sometimes, you need to go a bit deeper with a test to understand which users are seeing which variant, or enforce a certain variant for a user. Laboratory has a number of tools to help you do this.
163
+
164
+ **Finding all participants in a variant**:
165
+
166
+ ```ruby
167
+ experiment = Laboratory::Experiment.find('blue_button_cta')
168
+ control = experiment.variants.first
169
+
170
+ control.participants_id
171
+ ```
172
+
173
+ **Setting a user to a specific variant**:
174
+
175
+ ```ruby
176
+ experiment = Laboratory::Experiment.find('blue_button_cta')
177
+ user = Laboratory::User.new(id: 1)
178
+
179
+ experiment.assign_to_variant('control', user: user)
180
+ ```
181
+
182
+ Note the `#assign_to_variant` method also takes an optional user parameter should you want to define the user specifically in this case (like above). It defaults to a user with the current_user_id defined in the Laboratory configuration if you omit it.
183
+
184
+ **Fetching the changelog for an experiment**
185
+
186
+ ```ruby
187
+ experiment = Laboratory::Experiment.find('blue_button_cta')
188
+ experiment.changelog
189
+ ```
190
+
191
+ **Finding all the experiments a user is in**:
192
+
193
+ ```ruby
194
+ user = Laboratory::User.new(id: 1)
195
+ user.experiments
196
+ ```
197
+
198
+ **Finding the variant a user is in for a specific experiment**:
199
+
200
+ ```ruby
201
+ experiment = Laboratory::Experiment.find('blue_button_cta')
202
+ user = Laboratory::User.new(id: 1)
203
+
204
+ user.variant_for_experiment(experiment) # Note: This returns nil if the user is not in the experiment
205
+ ```
206
+
207
+ **Updating an experiment's variants**:
208
+
209
+ Note: This would wipe all users from the experiment.
210
+
211
+ ```ruby
212
+ experiment = Laboratory::Experiment.find('blue_button_cta')
213
+ variants = [
214
+ {
215
+ id: 'control',
216
+ percentage: 40
217
+ },
218
+ {
219
+ id: 'variant_a',
220
+ percentage: 60
221
+ }
222
+ ]
223
+
224
+ experiment.update(variants: new_variants)
225
+ ```
226
+
227
+ **Finding the current user**:
228
+
229
+ The following will return a Laboratory::User object with the user id matching the current_user_id defined in the Laboratory configuration.
230
+
231
+ ```ruby
232
+ Laboratory::Config.current_user
233
+ ```
234
+
235
+
236
+ ### Building your own adapters and algorithms
237
+
238
+ **Adapters**:
239
+
240
+ Any adapter just needs to the respond to the following methods:
241
+
242
+ * `#write(experiment)`
243
+ * `#read(experiment_id)`
244
+ * `#read_all`
245
+ * `#delete(experiment_id)`
246
+ * `#delete_all`
247
+
248
+ **Algorithm**:
249
+
250
+ Any algorithm just needs to respond to a `#pick!(variants)` and a `#id` method, and needs to be added to the `Laboratory::Algorithms#ALGORITHMS` definition. The `#id` method returns an identifier that is used for serialisation purposes.
251
+
252
+ ## Development
253
+
254
+ After checking out the repo, run `bin/setup` to install dependencies. Then, run `rake spec` to run the tests. You can also run `bin/console` for an interactive prompt that will allow you to experiment.
255
+
256
+ To install this gem onto your local machine, run `bundle exec rake install`. To release a new version, update the version number in `version.rb`, and then run `bundle exec rake release`, which will create a git tag for the version, push git commits and tags, and push the `.gem` file to [rubygems.org](https://rubygems.org).
257
+
258
+ ## Contributing
259
+
260
+ Bug reports and pull requests are welcome on GitHub at https://github.com/butternutbox/laboratory. This project is intended to be a safe, welcoming space for collaboration, and contributors are expected to adhere to that.
261
+
262
+
263
+ ## License
264
+
265
+ The gem is available as open source under the terms of the [MIT License](https://opensource.org/licenses/MIT).
data/Rakefile ADDED
@@ -0,0 +1,6 @@
1
+ require "bundler/gem_tasks"
2
+ require "rspec/core/rake_task"
3
+
4
+ RSpec::Core::RakeTask.new(:spec)
5
+
6
+ task :default => :spec
data/bin/console ADDED
@@ -0,0 +1,14 @@
1
+ #!/usr/bin/env ruby
2
+
3
+ require "bundler/setup"
4
+ require "laboratory"
5
+
6
+ # You can add fixtures and/or initialization code here to make experimenting
7
+ # with your gem easier. You can also use a different console, if you like.
8
+
9
+ # (If you use this, don't forget to add pry to your Gemfile!)
10
+ # require "pry"
11
+ # Pry.start
12
+
13
+ require "irb"
14
+ IRB.start(__FILE__)
data/bin/setup ADDED
@@ -0,0 +1,8 @@
1
+ #!/usr/bin/env bash
2
+ set -euo pipefail
3
+ IFS=$'\n\t'
4
+ set -vx
5
+
6
+ bundle install
7
+
8
+ # Do any other automated setup that you need to do here
@@ -0,0 +1,32 @@
1
+ require_relative 'lib/laboratory/version'
2
+
3
+ Gem::Specification.new do |spec|
4
+ spec.name = 'laboratory'
5
+ spec.version = Laboratory::VERSION
6
+ spec.authors = ['Niall Paterson']
7
+ spec.email = ['niall@butternutbox.com']
8
+
9
+ spec.summary = 'Laboratory: An A/B Testing and Feature Flag system for Ruby'
10
+ spec.description = 'Laboratory: An A/B Testing and Feature Flag system for Ruby'
11
+ spec.homepage = 'https://github.com/butternutbox/laboratory'
12
+ spec.license = 'MIT'
13
+ spec.required_ruby_version = Gem::Requirement.new('>= 2.3.0')
14
+
15
+ spec.metadata['homepage_uri'] = spec.homepage
16
+ spec.metadata['source_code_uri'] = 'https://github.com/butternutbox/laboratory'
17
+ spec.metadata['changelog_uri'] = 'https://github.com/butternutbox/laboratory/releases'
18
+
19
+ # Specify which files should be added to the gem when it is released.
20
+ # The `git ls-files -z` loads the files in the RubyGem that have been added into git.
21
+ spec.files = Dir.chdir(File.expand_path(__dir__)) do
22
+ `git ls-files -z`.split("\x0").reject { |f| f.match(%r{^(test|spec|features)/}) }
23
+ end
24
+ spec.bindir = 'exe'
25
+ spec.executables = spec.files.grep(%r{^exe/}) { |f| File.basename(f) }
26
+ spec.require_paths = ['lib']
27
+
28
+ spec.add_dependency 'redis', '>= 2.1'
29
+
30
+ spec.add_development_dependency 'rspec', '~> 3.8'
31
+ spec.add_development_dependency 'fakeredis', '~> 0.8'
32
+ end
@@ -0,0 +1,31 @@
1
+ module Laboratory
2
+ module Adapters
3
+ class MockAdapter
4
+ attr_accessor :experiment_hash
5
+
6
+ def initialize
7
+ @experiment_hash = {}
8
+ end
9
+
10
+ def write(experiment)
11
+ experiment_hash[experiment.id] = experiment
12
+ end
13
+
14
+ def read_all
15
+ experiment_hash.values
16
+ end
17
+
18
+ def read(experiment_id)
19
+ experiment_hash[experiment_id]
20
+ end
21
+
22
+ def delete(experiment_id)
23
+ experiment_hash.delete(experiment_id)
24
+ end
25
+
26
+ def delete_all
27
+ @experiment_hash = {}
28
+ end
29
+ end
30
+ end
31
+ end
@@ -0,0 +1,149 @@
1
+ module Laboratory
2
+ module Adapters
3
+ class RedisAdapter
4
+ attr_reader :redis
5
+
6
+ ALL_EXPERIMENTS_KEYS_KEY = 'SWITCH_ALL_EXPERIMENT_KEYS'.freeze
7
+
8
+ def initialize(url:)
9
+ @redis = Redis.new(url: url)
10
+
11
+ if !redis.get(ALL_EXPERIMENTS_KEYS_KEY)
12
+ redis.set(ALL_EXPERIMENTS_KEYS_KEY, [])
13
+ end
14
+ end
15
+
16
+ def write(experiment)
17
+ redis.set(redis_key(experiment_id: experiment.id), experiment_to_json(experiment))
18
+
19
+ # Write to ALL_EXPERIMENTS_KEY_KEY if it isn't already there.
20
+ experiment_ids = JSON.parse(redis.get(ALL_EXPERIMENTS_KEYS_KEY))
21
+ experiment_ids << experiment.id unless experiment_ids.include?(experiment.id)
22
+ redis.set(ALL_EXPERIMENTS_KEYS_KEY, experiment_ids.to_json)
23
+ end
24
+
25
+ def read(experiment_id)
26
+ key = redis_key(experiment_id: experiment_id)
27
+ response = redis.get(key)
28
+
29
+ return nil if response.nil?
30
+ parse_json_to_experiment(JSON.parse(response))
31
+ end
32
+
33
+ def read_all
34
+ experiment_ids = JSON.parse(redis.get(ALL_EXPERIMENTS_KEYS_KEY))
35
+ experiment_ids.map do |experiment_id|
36
+ read(experiment_id)
37
+ end
38
+ end
39
+
40
+ def delete(experiment_id)
41
+ key = redis_key(experiment_id: experiment_id)
42
+ redis.del(key)
43
+
44
+ # Remove from ALL_EXPERIMENTS_KEY_KEY
45
+ experiment_ids = JSON.parse(redis.get(ALL_EXPERIMENTS_KEYS_KEY))
46
+ experiment_ids.delete(experiment_id)
47
+ redis.set(ALL_EXPERIMENTS_KEYS_KEY, experiment_ids.to_json)
48
+ end
49
+
50
+ def delete_all
51
+ experiment_ids = JSON.parse(redis.get(ALL_EXPERIMENTS_KEYS_KEY))
52
+ experiment_ids.each { |experiment_id| delete(experiment_id) }
53
+ end
54
+
55
+ private
56
+
57
+ def redis_key(experiment_id:)
58
+ "laboratory_#{experiment_id}"
59
+ end
60
+
61
+ def experiment_to_json(experiment)
62
+ {
63
+ id: experiment.id,
64
+ algorithm: experiment.algorithm.id,
65
+ variants: experiment_variants_to_hash(experiment.variants),
66
+ changelog: experiment.changelog
67
+ }.to_json
68
+ end
69
+
70
+ def experiment_variants_to_hash(variants)
71
+ variants.map do |variant|
72
+ {
73
+ id: variant.id,
74
+ percentage: variant.percentage,
75
+ participant_ids: variant.participant_ids,
76
+ events: experiment_events_to_hash(variant.events)
77
+ }
78
+ end
79
+ end
80
+
81
+ def experiment_events_to_hash(events)
82
+ events.map do |event|
83
+ {
84
+ id: event.id,
85
+ event_recordings: experiment_event_recordings_to_hash(event.event_recordings)
86
+ }
87
+ end
88
+ end
89
+
90
+ def experiment_event_recordings_to_hash(event_recordings)
91
+ event_recordings.map do |event_recording|
92
+ {
93
+ user_id: event_recording.user_id,
94
+ timestamp: event_recording.timestamp
95
+ }
96
+ end
97
+ end
98
+
99
+ def parse_json_to_experiment(json)
100
+ Experiment.new(
101
+ id: json['id'],
102
+ algorithm: Algorithms.to_class(json['algorithm']),
103
+ variants: parse_json_to_experiment_variants(json['variants']),
104
+ changelog: parse_json_to_experiment_changelog_items(json['changelog'])
105
+ )
106
+ end
107
+
108
+ def parse_json_to_experiment_variants(variants_json)
109
+ variants_json.map do |json|
110
+ Experiment::Variant.new(
111
+ id: json['id'],
112
+ percentage: json['percentage'],
113
+ participant_ids: json['participant_ids'],
114
+ events: parse_json_to_experiment_events(json['events'])
115
+ )
116
+ end
117
+ end
118
+
119
+ def parse_json_to_experiment_changelog_items(changelog_json)
120
+ changelog_json.map do |json|
121
+ Experiment::ChangelogItems.new(
122
+ action: json[:action],
123
+ changes: json[:changes],
124
+ timestamp: json[:timestamp],
125
+ actor: json[:actor]
126
+ )
127
+ end
128
+ end
129
+
130
+ def parse_json_to_experiment_events(events_json)
131
+ events_json.map do |json|
132
+ Experiment::Event.new(
133
+ id: json['id'],
134
+ event_recordings: parse_json_to_experiment_event_recordings(json['event_recordings'])
135
+ )
136
+ end
137
+ end
138
+
139
+ def parse_json_to_experiment_event_recordings(event_recordings_json)
140
+ event_recordings_json.map do |json|
141
+ Experiment::Event::Recording.new(
142
+ user_id: json['user_id'],
143
+ timestamp: json['timestamp']
144
+ )
145
+ end
146
+ end
147
+ end
148
+ end
149
+ end
@@ -0,0 +1,13 @@
1
+ module Laboratory
2
+ module Algorithms
3
+ class Random
4
+ def self.pick!(variants)
5
+ variants.sort_by { |variant| - variant.percentage * rand() }.first
6
+ end
7
+
8
+ def self.id
9
+ 'RANDOM'
10
+ end
11
+ end
12
+ end
13
+ end
@@ -0,0 +1,11 @@
1
+ module Laboratory
2
+ module Algorithms
3
+ ALGORITHMS = [
4
+ Laboratory::Algorithms::Random
5
+ ].freeze
6
+
7
+ def self.to_class(algorithm_id)
8
+ ALGORITHMS.find { |algorithm_class| algorithm_class.id == algorithm_id }
9
+ end
10
+ end
11
+ end
@@ -0,0 +1,17 @@
1
+ module Laboratory
2
+ class Config
3
+ class << self
4
+ attr_accessor(
5
+ :current_user_id,
6
+ :adapter,
7
+ :actor,
8
+ :on_assignment_to_variant,
9
+ :on_event_recorded
10
+ )
11
+
12
+ def current_user
13
+ @current_user ||= Laboratory::User.new(id: current_user_id)
14
+ end
15
+ end
16
+ end
17
+ end
@@ -0,0 +1,14 @@
1
+ module Laboratory
2
+ class Experiment
3
+ class ChangelogItem
4
+ attr_reader :action, :changes, :timestamp, :actor
5
+
6
+ def initialize(action:, changes: [], timestamp:, actor:)
7
+ @action = action
8
+ @changes = changes
9
+ @timestamp = timestamp
10
+ @actor = actor
11
+ end
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,14 @@
1
+ module Laboratory
2
+ class Experiment
3
+ class Event
4
+ class Recording
5
+ attr_reader :user_id, :timestamp
6
+
7
+ def initialize(user_id:, timestamp: Time.now)
8
+ @user_id = user_id
9
+ @timestamp = timestamp
10
+ end
11
+ end
12
+ end
13
+ end
14
+ end
@@ -0,0 +1,12 @@
1
+ module Laboratory
2
+ class Experiment
3
+ class Event
4
+ attr_reader :id, :event_recordings
5
+
6
+ def initialize(id:, event_recordings: [])
7
+ @id = id
8
+ @event_recordings = event_recordings
9
+ end
10
+ end
11
+ end
12
+ end
@@ -0,0 +1,18 @@
1
+ module Laboratory
2
+ class Experiment
3
+ class Variant
4
+ attr_reader :id, :percentage, :participant_ids, :events
5
+
6
+ def initialize(id:, percentage:, participant_ids: [], events: [])
7
+ @id = id
8
+ @percentage = percentage
9
+ @participant_ids = participant_ids
10
+ @events = events
11
+ end
12
+
13
+ def add_participant(user)
14
+ participant_ids << user.id
15
+ end
16
+ end
17
+ end
18
+ end
@@ -0,0 +1,213 @@
1
+ module Laboratory
2
+ class Experiment
3
+ class UserNotInExperimentError < StandardError; end
4
+ class ClashingExperimentIdError < StandardError; end
5
+ class MissingExperimentIdError < StandardError; end
6
+ class MissingExperimentAlgorithmError < StandardError; end
7
+ class InvalidExperimentVariantFormatError < StandardError; end
8
+ class IncorrectPercentageTotalError < StandardError; end
9
+
10
+ attr_reader :id, :variants, :algorithm, :changelog
11
+
12
+ def initialize(id:, variants:, algorithm: Algorithms::Random, changelog: [])
13
+ @id = id
14
+ @algorithm = algorithm
15
+ @changelog = changelog
16
+
17
+ # We want to allow users to input Variant objects, or simple hashes.
18
+ # This also helps when decoding from adapters
19
+
20
+ @variants =
21
+ if variants.all? { |variant| variant.instance_of?(Laboratory::Experiment::Variant) }
22
+ variants
23
+ elsif variants.all? { |variant| variant.instance_of?(Hash) }
24
+ variants.map do |variant|
25
+ Variant.new(
26
+ id: variant[:id],
27
+ percentage: variant[:percentage],
28
+ participant_ids: [],
29
+ events: []
30
+ )
31
+ end
32
+ end
33
+ end
34
+
35
+ def self.all
36
+ Laboratory.config.adapter.read_all
37
+ end
38
+
39
+ def self.create(id:, variants:, algorithm: Algorithms::Random)
40
+ raise ClashingExperimentIdError if find(id)
41
+
42
+ changelog_item = Laboratory::Experiment::ChangelogItem.new(
43
+ action: :create,
44
+ changes: [],
45
+ timestamp: Time.now,
46
+ actor: Laboratory::Config.actor
47
+ )
48
+
49
+ experiment = Experiment.new(
50
+ id: id,
51
+ variants: variants,
52
+ algorithm: algorithm,
53
+ changelog: [changelog_item]
54
+ )
55
+
56
+ experiment.write!
57
+ experiment
58
+ end
59
+
60
+ def self.find(id)
61
+ Laboratory.config.adapter.read(id)
62
+ end
63
+
64
+ def self.find_or_create(id:, variants:, algorithm: Algorithms::Random)
65
+ find(id) || create(id: id, variants: variants, algorithm: algorithm)
66
+ end
67
+
68
+ def update(attrs)
69
+ # delete previous key if valid? passes below.
70
+ old_id = id
71
+
72
+ # Diff changes
73
+
74
+ current_hash = {
75
+ id: id,
76
+ variants: variants.map { |variant|
77
+ {
78
+ id: variant.id,
79
+ percentage: variant.percentage
80
+ }
81
+ },
82
+ algorithm: algorithm
83
+ }
84
+
85
+ updated_variants_subhash = attrs[:variants]&.map do |variant|
86
+ {
87
+ id: variant[:id],
88
+ percentage: variant[:percentage]
89
+ }
90
+ end
91
+
92
+ updated_hash = {
93
+ id: attrs[:id] || id,
94
+ variants: updated_variants_subhash || current_hash[:variants],
95
+ algorithm: attrs[:algorithm] || algorithm
96
+ }
97
+
98
+ changes = current_hash.to_a - updated_hash.to_a
99
+ @id = attrs[:id] if !attrs[:id].nil?
100
+ @variants = attrs[:variants] if !attrs[:variants].nil?
101
+ @algorithm = attrs[:algorithm] if !attrs[:algorithm].nil?
102
+
103
+ raise errors.first unless valid?
104
+
105
+ changelog_item = Laboratory::Experiment::ChangelogItem.new(
106
+ action: :update,
107
+ changes: changes,
108
+ timestamp: Time.now,
109
+ actor: Laboratory.config.actor
110
+ )
111
+
112
+ @changelog << changelog_item
113
+
114
+ Laboratory.config.adapter.delete(old_id)
115
+ write!
116
+ self
117
+ end
118
+
119
+ def delete
120
+ Laboratory.config.adapter.delete(id)
121
+ nil
122
+ end
123
+
124
+ def variant(user: Laboratory.config.current_user)
125
+ selected_variant = variants.find { |variant| variant.participant_ids.include?(user.id)}
126
+ return selected_variant if !selected_variant.nil?
127
+
128
+ variant = algorithm.pick!(variants)
129
+ variant.add_participant(user)
130
+
131
+ Laboratory::Config.on_assignment_to_variant&.call(self, variant, user)
132
+
133
+ write!
134
+ variant
135
+ end
136
+
137
+ def assign_to_variant(variant_id, user: Laboratory.config.current_user)
138
+ variants.each do |variant|
139
+ variant.participant_ids.delete(user.id)
140
+ end
141
+
142
+ variant = variants.find { |s| s.id == variant_id }
143
+ variant.add_participant(user)
144
+
145
+ Laboratory::Config.on_assignment_to_variant&.call(self, variant, user)
146
+
147
+ write!
148
+ variant
149
+ end
150
+
151
+ def record_event!(event_id, user: Laboratory.config.current_user)
152
+ variant = variants.find { |s| s.participant_ids.include?(user.id) }
153
+ raise UserNotInExperimentError unless variant
154
+
155
+ maybe_event = variant.events.find { |event| event.id == event_id }
156
+ event =
157
+ if maybe_event != nil
158
+ maybe_event
159
+ else
160
+ e = Event.new(id: event_id)
161
+ variant.events << e
162
+ e
163
+ end
164
+ event_recording = Event::Recording.new(user_id: user.id)
165
+
166
+ event.event_recordings << event_recording
167
+
168
+ Laboratory::Config.on_event_recorded&.call(self, variant, user, event)
169
+
170
+ write!
171
+ event_recording
172
+ end
173
+
174
+ def write!
175
+ raise errors.first unless valid?
176
+ Laboratory.config.adapter.write(self)
177
+ end
178
+
179
+ def valid?
180
+ valid_variants =
181
+ variants.all? do |variant|
182
+ !variant.id.nil? && !variant.percentage.nil?
183
+ end
184
+
185
+ valid_percentage_amounts =
186
+ variants.map(&:percentage).sum == 100
187
+
188
+ !id.nil? && !algorithm.nil? && valid_variants && valid_percentage_amounts
189
+ end
190
+
191
+ def errors
192
+ errors = []
193
+
194
+ missing_variant_ids = variants.any? do |variant|
195
+ variant.id.nil?
196
+ end
197
+
198
+ missing_variant_percentages = variants.any? do |variant|
199
+ variant.percentage.nil?
200
+ end
201
+
202
+ incorrect_percentage_total = variants.map(&:percentage).sum != 100
203
+
204
+ errors << MissingExperimentIdError if id.nil?
205
+ errors << MissingExperimentAlgorithmError if algorithm.nil?
206
+ errors << MissingExperimentVariantIdError if missing_variant_ids
207
+ errors << MissingExperimentVariantPercentageError if missing_variant_percentages
208
+ errors << IncorrectPercentageTotalError if incorrect_percentage_total
209
+
210
+ errors
211
+ end
212
+ end
213
+ end
@@ -0,0 +1,23 @@
1
+ module Laboratory
2
+ class User
3
+ attr_reader :id
4
+
5
+ def initialize(id:)
6
+ @id = id
7
+ end
8
+
9
+ def experiments
10
+ Experiment.all.select do |experiment|
11
+ experiment.variants.any? do |variant|
12
+ variant.participant_ids.include?(id)
13
+ end
14
+ end
15
+ end
16
+
17
+ def variant_for_experiment(experiment)
18
+ experiment.variants.find do |variant|
19
+ variant.participant_ids.include?(id)
20
+ end
21
+ end
22
+ end
23
+ end
@@ -0,0 +1,3 @@
1
+ module Laboratory
2
+ VERSION = "0.1.0"
3
+ end
data/lib/laboratory.rb ADDED
@@ -0,0 +1,20 @@
1
+ require 'laboratory/version'
2
+ require 'laboratory/config'
3
+ require 'laboratory/user'
4
+ require 'laboratory/adapters/redis_adapter'
5
+ require 'laboratory/adapters/mock_adapter'
6
+ require 'laboratory/algorithms/random'
7
+ require 'laboratory/algorithms'
8
+ require 'laboratory/experiment'
9
+ require 'laboratory/experiment/variant'
10
+ require 'laboratory/experiment/changelog_item'
11
+ require 'laboratory/experiment/event'
12
+ require 'laboratory/experiment/event/recording'
13
+
14
+ module Laboratory
15
+ class << self
16
+ def config
17
+ Laboratory::Config
18
+ end
19
+ end
20
+ end
metadata ADDED
@@ -0,0 +1,113 @@
1
+ --- !ruby/object:Gem::Specification
2
+ name: laboratory
3
+ version: !ruby/object:Gem::Version
4
+ version: 0.1.0
5
+ platform: ruby
6
+ authors:
7
+ - Niall Paterson
8
+ autorequire:
9
+ bindir: exe
10
+ cert_chain: []
11
+ date: 2020-03-20 00:00:00.000000000 Z
12
+ dependencies:
13
+ - !ruby/object:Gem::Dependency
14
+ name: redis
15
+ requirement: !ruby/object:Gem::Requirement
16
+ requirements:
17
+ - - ">="
18
+ - !ruby/object:Gem::Version
19
+ version: '2.1'
20
+ type: :runtime
21
+ prerelease: false
22
+ version_requirements: !ruby/object:Gem::Requirement
23
+ requirements:
24
+ - - ">="
25
+ - !ruby/object:Gem::Version
26
+ version: '2.1'
27
+ - !ruby/object:Gem::Dependency
28
+ name: rspec
29
+ requirement: !ruby/object:Gem::Requirement
30
+ requirements:
31
+ - - "~>"
32
+ - !ruby/object:Gem::Version
33
+ version: '3.8'
34
+ type: :development
35
+ prerelease: false
36
+ version_requirements: !ruby/object:Gem::Requirement
37
+ requirements:
38
+ - - "~>"
39
+ - !ruby/object:Gem::Version
40
+ version: '3.8'
41
+ - !ruby/object:Gem::Dependency
42
+ name: fakeredis
43
+ requirement: !ruby/object:Gem::Requirement
44
+ requirements:
45
+ - - "~>"
46
+ - !ruby/object:Gem::Version
47
+ version: '0.8'
48
+ type: :development
49
+ prerelease: false
50
+ version_requirements: !ruby/object:Gem::Requirement
51
+ requirements:
52
+ - - "~>"
53
+ - !ruby/object:Gem::Version
54
+ version: '0.8'
55
+ description: 'Laboratory: An A/B Testing and Feature Flag system for Ruby'
56
+ email:
57
+ - niall@butternutbox.com
58
+ executables: []
59
+ extensions: []
60
+ extra_rdoc_files: []
61
+ files:
62
+ - ".gitignore"
63
+ - ".rspec"
64
+ - ".travis.yml"
65
+ - CODE_OF_CONDUCT.md
66
+ - Gemfile
67
+ - Gemfile.lock
68
+ - LICENSE.txt
69
+ - README.md
70
+ - Rakefile
71
+ - bin/console
72
+ - bin/setup
73
+ - laboratory.gemspec
74
+ - lib/laboratory.rb
75
+ - lib/laboratory/adapters/mock_adapter.rb
76
+ - lib/laboratory/adapters/redis_adapter.rb
77
+ - lib/laboratory/algorithms.rb
78
+ - lib/laboratory/algorithms/random.rb
79
+ - lib/laboratory/config.rb
80
+ - lib/laboratory/experiment.rb
81
+ - lib/laboratory/experiment/changelog_item.rb
82
+ - lib/laboratory/experiment/event.rb
83
+ - lib/laboratory/experiment/event/recording.rb
84
+ - lib/laboratory/experiment/variant.rb
85
+ - lib/laboratory/user.rb
86
+ - lib/laboratory/version.rb
87
+ homepage: https://github.com/butternutbox/laboratory
88
+ licenses:
89
+ - MIT
90
+ metadata:
91
+ homepage_uri: https://github.com/butternutbox/laboratory
92
+ source_code_uri: https://github.com/butternutbox/laboratory
93
+ changelog_uri: https://github.com/butternutbox/laboratory/releases
94
+ post_install_message:
95
+ rdoc_options: []
96
+ require_paths:
97
+ - lib
98
+ required_ruby_version: !ruby/object:Gem::Requirement
99
+ requirements:
100
+ - - ">="
101
+ - !ruby/object:Gem::Version
102
+ version: 2.3.0
103
+ required_rubygems_version: !ruby/object:Gem::Requirement
104
+ requirements:
105
+ - - ">="
106
+ - !ruby/object:Gem::Version
107
+ version: '0'
108
+ requirements: []
109
+ rubygems_version: 3.0.1
110
+ signing_key:
111
+ specification_version: 4
112
+ summary: 'Laboratory: An A/B Testing and Feature Flag system for Ruby'
113
+ test_files: []