class EenyMeeny::Experiment

Constants

Attributes

end_at[R]
id[R]
name[R]
start_at[R]
total_weight[R]
variations[R]
version[R]

Public Class Methods

find_all() click to toggle source
# File lib/eeny-meeny/models/experiment.rb, line 15
def self.find_all
  return [] unless EenyMeeny.config.experiments
  EenyMeeny.config.experiments.map do |id, experiment|
    new(id, **experiment)
  end
end
find_by_id(experiment_id) click to toggle source
# File lib/eeny-meeny/models/experiment.rb, line 22
def self.find_by_id(experiment_id)
  return unless EenyMeeny.config.experiments
  experiment = EenyMeeny.config.experiments[experiment_id.to_sym]
  new(experiment_id, **experiment) if experiment
end
new(id, name: '', version: 1, variations: {}, start_at: nil, end_at: nil) click to toggle source
# File lib/eeny-meeny/models/experiment.rb, line 37
def initialize(id, name: '', version: 1, variations: {}, start_at: nil, end_at: nil)
  @id = id
  @name = name
  @version = version
  @variations = variations.map do |variation_id, variation|
    Variation.new(variation_id, **variation)
  end
  @total_weight = (@variations.empty? ? 1.0 : @variations.sum { |variation| variation.weight.to_f })
  @start_at = Time.zone.parse(start_at) if start_at
  @end_at = Time.zone.parse(end_at) if end_at
end

Public Instance Methods

active?(now = Time.zone.now) click to toggle source
# File lib/eeny-meeny/models/experiment.rb, line 49
def active?(now = Time.zone.now)
  return true if @start_at.nil? && @end_at.nil?
  return true if @end_at.nil? && (@start_at && (now > @start_at)) # specified start - open-ended
  return true if @start_at.nil? && (@end_at && (now < @end_at)) # unspecified start - specified end
  !!((@start_at && (now > @start_at)) && (@end_at && (now < @end_at))) # specified start and end
end
find_variation(variation_id) click to toggle source
# File lib/eeny-meeny/models/experiment.rb, line 56
def find_variation(variation_id)
  @variations.detect { |v| v.id.to_s == variation_id.to_s }
end
pick_variation() click to toggle source
# File lib/eeny-meeny/models/experiment.rb, line 60
def pick_variation
  Hash[
      @variations.map do |variation|
        [variation, variation.weight]
      end
  ].max_by { |_, weight| rand ** (@total_weight / weight) }.first
end