class Abnormal

Constants

MAJOR_VERSION
VERSION

Public Class Methods

ab_test(identity, test_name, alternatives, conversions) click to toggle source
# File lib/abnormal.rb, line 9
def self.ab_test(identity, test_name, alternatives, conversions)
  conversions = [conversions]  unless conversions.is_a? Array

  test_id = Digest::MD5.hexdigest(test_name)
  db['tests'].update(
    {:name => test_name, :_id => test_id},
    {
      :$set => {
        :alternatives => alternatives,
      },
      :$addToSet => {
        :conversions => {:$each => conversions}
      }
    },
    :upsert => true
  )

  conversions.each do |conversion|
    db['participations'].update(
      {
        :participant => identity,
        :test_id => test_id,
        :conversion => conversion
      },
      {
        :$set => {:conversions => 0}
      },
      :upsert => true
    )
  end

  chose_alternative(identity, test_name, alternatives)
end
chose_alternative(identity, test_name, alternatives) click to toggle source
# File lib/abnormal.rb, line 76
def self.chose_alternative(identity, test_name, alternatives)
  alternatives_array = normalize_alternatives(alternatives)
  index = Digest::MD5.hexdigest(test_name + identity).to_i(16) % alternatives_array.size
  alternatives_array[index]
end
convert!(identity, conversion) click to toggle source
# File lib/abnormal.rb, line 43
def self.convert!(identity, conversion)
  db['participations'].update(
    {
      :participant => identity,
      :conversion => conversion
    },
    {
      :$inc => {:conversions => 1}
    },
    :multi => true
  )
end
db() click to toggle source
# File lib/abnormal.rb, line 4
def self.db; @@db; end
db=(db) click to toggle source
# File lib/abnormal.rb, line 5
def self.db=(db)
  @@db = db
end
get_participation(id, test_name, conversion) click to toggle source
# File lib/abnormal.rb, line 64
def self.get_participation(id, test_name, conversion)
  db['participations'].find_one(
    :participant => id,
    :test_id => Digest::MD5.hexdigest(test_name),
    :conversion => conversion
  )
end
get_test(test_id) click to toggle source
# File lib/abnormal.rb, line 56
def self.get_test(test_id)
  db['tests'].find_one(:_id => test_id)
end
normalize_alternatives(alternatives) click to toggle source
# File lib/abnormal.rb, line 82
def self.normalize_alternatives(alternatives)
  case alternatives
  when Array
    alternatives
  when Hash
    alternatives_array = []
    idx = 0
    alternatives.each{|k,v| alternatives_array.fill(k, idx, v); idx += v}
    alternatives_array
  when Range
    alternatives.to_a
  end
end
participations() click to toggle source
# File lib/abnormal.rb, line 72
def self.participations
  db['participations'].find.to_a
end
tests() click to toggle source
# File lib/abnormal.rb, line 60
def self.tests
  db['tests'].find.to_a
end