Class: Notches::Hit

Inherits:
ActiveRecord::Base
  • Object
show all
Defined in:
app/models/notches/hit.rb

Class Method Summary collapse

Class Method Details

.log(attributes) ⇒ Object



19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
# File 'app/models/notches/hit.rb', line 19

def self.log(attributes)
  attributes[:user_agent] ||= ''
  hit = self.new
  hit.transaction do
    Rails.logger.info("[Notches] Tracking #{attributes.inspect} at #{Date.today} #{Time.now}")
    now            = Time.zone.now
    hit.url        = Notches::URL.find_or_create_by(url: attributes[:url])
    hit.user_agent = Notches::UserAgent.find_or_create_by(
      user_agent_md5: Digest::MD5.hexdigest(attributes[:user_agent]),
      :user_agent => attributes[:user_agent]
    )
    hit.session = Notches::Session.find_or_create_by(session_id: attributes[:session_id])
    hit.ip      = Notches::IP.find_or_create_by(ip: attributes[:ip])
    hit.date    = Notches::Date.find_or_create_by(date: now.to_date)
    hit.time    = Notches::Time.find_or_create_by_time(now)

    if attributes[:user_id].present?
      Notches::UserSession.find_or_create_by(
        user_id: attributes[:user_id],
        notches_session_id: hit.session.id
      )
    end

    begin
      hit.save!
    rescue
      Rails.logger.info "Skipping non-unique hit"
    end
  end
  hit
end