Class: AB::Test

Inherits:
Object
  • Object
show all
Defined in:
lib/ab/test.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, description) ⇒ Test

Returns a new instance of Test.



5
6
7
# File 'lib/ab/test.rb', line 5

def initialize(name, description)
  @name, @description, @alternatives, @last_percent= name, description, [], 0
end

Instance Attribute Details

#alternativesObject (readonly)

Returns the value of attribute alternatives.



3
4
5
# File 'lib/ab/test.rb', line 3

def alternatives
  @alternatives
end

#descriptionObject (readonly)

Returns the value of attribute description.



3
4
5
# File 'lib/ab/test.rb', line 3

def description
  @description
end

#nameObject (readonly)

Returns the value of attribute name.



3
4
5
# File 'lib/ab/test.rb', line 3

def name
  @name
end

Instance Method Details

#alternative(name, options = {}, &value_proc) ⇒ Object



9
10
11
12
13
# File 'lib/ab/test.rb', line 9

def alternative(name, options={}, &value_proc)
  alternative = AB::Alternative.new(self, name, options, &value_proc)
  alternatives << alternative
  alternative
end

#get_alternative(identity) ⇒ Object



24
25
26
27
28
29
30
31
32
33
34
35
36
# File 'lib/ab/test.rb', line 24

def get_alternative(identity)
  return @using if @using

  if identity.nil?
    return alternatives.first
  end

  if alternatives.any?(&:percent)
    alternatives.detect { |alternative| alternative.range.include?(identity % 100) }
  else
    alternatives[identity % alternatives.size]
  end
end

#resultsObject



50
51
52
# File 'lib/ab/test.rb', line 50

def results
  alternatives.map(&:results)
end

#update_percentage_range(alternative) ⇒ Object



38
39
40
41
42
# File 'lib/ab/test.rb', line 38

def update_percentage_range(alternative)
  percent = alternative.percent - 1
  alternative.range = @last_percent..(@last_percent + percent)
  @last_percent = alternative.range.last + 1
end

#use(name) ⇒ Object



15
16
17
18
19
20
21
22
# File 'lib/ab/test.rb', line 15

def use(name)
  begin
    @using = alternatives.detect { |alternative| alternative.name == name }
    yield
  ensure
    @using = nil
  end
end

#verify_percentagesObject

Raises:

  • (ArgumentError)


44
45
46
47
48
# File 'lib/ab/test.rb', line 44

def verify_percentages
  return unless alternatives.any?(&:percent)
  raise ArgumentError.new("Some alternatives are missing percentages") unless alternatives.all?(&:percent)
  raise ArgumentError.new("Percentages must add up to 100") unless @last_percent == 100
end