Module: Vanity::Metric::ActiveRecord

Defined in:
lib/vanity/metric/active_record.rb

Overview

Calling model method on a metric extends it with these modules, redefining the values and track! methods.

Since:

  • 1.3.0

Instance Method Summary collapse

Instance Method Details

#after_create(record) ⇒ Object

AR model after_create callback notifies all the hooks.

Since:

  • 1.3.0



101
102
103
104
105
106
107
108
109
110
111
# File 'lib/vanity/metric/active_record.rb', line 101

def after_create(record)
  return unless @playground.collecting?
  count = @ar_column ? (record.send(@ar_column) || 0) : 1

  identity = Vanity.context.vanity_identity rescue nil
  identity ||= if @ar_identity_block
    @ar_identity_block.call(record)
  end

  call_hooks record.send(@ar_timestamp), identity, [count] if count > 0 && @ar_scoped.exists?(record.id)
end

#last_update_atObject

Since:

  • 1.3.0



94
95
96
97
98
# File 'lib/vanity/metric/active_record.rb', line 94

def last_update_at
  # SELECT created_at FROM "skies" ORDER BY created_at DESC LIMIT 1
  record = @ar_scoped.order("#{@ar_timestamp} DESC").select(@ar_timestamp).first
  record && record.send(@ar_timestamp)
end

#track!(args = nil) ⇒ Object

This track! method stores nothing, but calls the hooks.

Since:

  • 1.3.0



89
90
91
92
# File 'lib/vanity/metric/active_record.rb', line 89

def track!(args = nil)
  return unless @playground.collecting?
  call_hooks(*track_args(args))
end

#values(sdate, edate) ⇒ Object

This values method queries the database.

Since:

  • 1.3.0



68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
# File 'lib/vanity/metric/active_record.rb', line 68

def values(sdate, edate)
  time = Time.now.in_time_zone
  difference = time.to_date - Date.today
  sdate = sdate + difference
  edate = edate + difference

  grouped = @ar_scoped
      .where(@ar_timestamp_table => { @ar_timestamp => (sdate.to_time...(edate + 1).to_time) })
      .group("date(#{@ar_scoped.quoted_table_name}.#{@ar_scoped.connection.quote_column_name(@ar_timestamp)})")

  if @ar_column
    grouped = grouped.send(@ar_aggregate, @ar_column)
  else
    grouped = grouped.count
  end

  grouped = Hash[grouped.map {|k,v| [k.to_date, v] }]
  (sdate..edate).inject([]) { |ordered, date| ordered << (grouped[date] || 0) }
end