Class: GreenFlag::SiteVisitor

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
app/models/green_flag/site_visitor.rb

Overview

A SiteVisitor is a unique visitor to the site.

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.for_user!(user, visitor_to_check = nil) ⇒ Object

Finds, updates, or creates a SiteVisitor for the given user. If the user has an existing SiteVisitor, return that Otherwise, check if the given SiteVisitor can be assigned to the user. Otherwise, create a brand new SiteVisitor



13
14
15
16
17
18
19
20
# File 'app/models/green_flag/site_visitor.rb', line 13

def self.for_user!(user, visitor_to_check=nil)
  where(user_id: user.id).first ||
    assign_visitor_if_available(visitor_to_check, user) ||
    create!(user_id: user.id, visitor_code: new_code)
rescue ActiveRecord::RecordNotUnique, PG::Error => ex
  # Race condition - some other request created/updated a SiteVisitor with our user's id
  where(user_id: user.id).first || raise
end

.for_visitor_code!(code) ⇒ Object



22
23
24
25
26
27
# File 'app/models/green_flag/site_visitor.rb', line 22

def self.for_visitor_code!(code)
  where(visitor_code: code).first_or_create!
rescue ActiveRecord::RecordNotUnique, PG::Error => ex
  # Race condition
  where(visitor_code: code).first || raise
end

.new_codeObject



29
30
31
# File 'app/models/green_flag/site_visitor.rb', line 29

def self.new_code
  SecureRandom.uuid
end

Instance Method Details

#first_visited_atObject

If GreenFlag is added to an existing app, then some users might be older than their corresponding SiteVisitors



35
36
37
# File 'app/models/green_flag/site_visitor.rb', line 35

def first_visited_at
  [created_at, user.try(:created_at), DateTime.now].compact.min
end