Module: FieldTest::Helpers

Defined in:
lib/field_test/helpers.rb

Instance Method Summary collapse

Instance Method Details

#field_test(experiment, options = {}) ⇒ Object



3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
# File 'lib/field_test/helpers.rb', line 3

def field_test(experiment, options = {})
  exp = FieldTest::Experiment.find(experiment)

  participants = field_test_participants(options)

  if try(:request)
    if params[:field_test] && params[:field_test][experiment]
      options[:variant] ||= params[:field_test][experiment]
    end

    if FieldTest.exclude_bots?
      options[:exclude] = Browser.new(request.user_agent).bot?
    end

    options[:ip] = request.remote_ip
    options[:user_agent] = request.user_agent
  end

  # cache results for request
  @field_test_cache ||= {}
  @field_test_cache[experiment] ||= exp.variant(participants, options)
end

#field_test_converted(experiment, options = {}) ⇒ Object



26
27
28
29
30
31
32
# File 'lib/field_test/helpers.rb', line 26

def field_test_converted(experiment, options = {})
  exp = FieldTest::Experiment.find(experiment)

  participants = field_test_participants(options)

  exp.convert(participants, goal: options[:goal])
end

#field_test_experiments(options = {}) ⇒ Object



34
35
36
37
38
39
40
41
42
43
44
# File 'lib/field_test/helpers.rb', line 34

def field_test_experiments(options = {})
  participants = field_test_participants(options)
  memberships = FieldTest::Membership.where(participant: participants).group_by(&:participant)
  experiments = {}
  participants.each do |participant|
    memberships[participant].to_a.each do |membership|
      experiments[membership.experiment] ||= membership.variant
    end
  end
  experiments
end

#field_test_participants(options = {}) ⇒ Object



46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
# File 'lib/field_test/helpers.rb', line 46

def field_test_participants(options = {})
  participants = []

  if options[:participant]
    participants << options[:participant]
  else
    if respond_to?(:current_user, true) && current_user
      participants << current_user
    end

    # controllers and views
    if try(:request)
      # use cookie
      cookie_key = "field_test"

      token = cookies[cookie_key]
      token = token.gsub(/[^a-z0-9\-]/i, "") if token

      if participants.empty? && !token
        token = SecureRandom.uuid
        cookies[cookie_key] = {value: token, expires: 30.days.from_now}
      end
      if token
        participants << token

        # backwards compatibility
        participants << "cookie:#{token}"
      end
    end

    # mailers
    to = try(:message).try(:to).try(:first)
    if to
      participants << to
    end
  end

  FieldTest::Participant.standardize(participants)
end