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



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

def after_create(record)
  return unless @playground.collecting?

  count = @ar_column ? (record.send(@ar_column) || 0) : 1

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

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

#last_update_atObject

Since:

  • 1.3.0



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

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



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

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



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

def values(sdate, edate)
  time = Time.now.in_time_zone
  difference = time.to_date - Date.today
  sdate += difference
  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)})")

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

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