Skip to content

Use Split outside a web request

André Luis Leal Cardoso Junior edited this page Sep 1, 2020 · 3 revisions

Even if you have set the Session type persistence for split, you can use your Redis to host custom keys.

# Begin the test for an object
experiment_name = 'my_experience'
key = "thing-#{thing.id}"
ab_user = Split::User.new(nil, Split::Persistence::RedisAdapter.new(nil, key))
experiment = Split::ExperimentCatalog.find_or_create(experiment_name, 'variant_A', 'variant_B')
trial = Split::Trial.new(user: ab_user, experiment: experiment)
trial.choose!
puts trial.alternative.name
# Finish the test for an object
experiment_name = 'my_experience'
key = "thing-#{thing.id}"
ab_user = Split::User.new(nil, Split::Persistence::RedisAdapter.new(nil, key))
experiment = Split::ExperimentCatalog.find_or_create(experiment_name, 'variant_A', 'variant_B')
trial = Split::Trial.new(user: ab_user, experiment: experiment)
trial.choose!
trial.complete!
# Getting active experiments from a given user

ab_user = Split::User.new(nil, Split::Persistence::RedisAdapter.new(nil, 'user_id'))
ab_user.active_experiments
# => {"link_text_2"=>"Click Here"}

I don't know why I have to call choose! on trial again, it seems that the trial's alternative can't be found. Anyway, because the key is the same, the alternative should not be changed.

Doing this will set a lot of redis objects and reset or delete the experiment will not delete them.

# Delete useless keys when you have finish your A/B test
redis = Redis.new(:url => "redis://localhost:6379/3")
keys = redis.keys("persistence:thing*")
keys.each do |k|
  redis.del(k)
end
Clone this wiki locally