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



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

def after_create(record)
  return unless @playground.collecting?
  count = @ar_column ? (record.send(@ar_column) || 0) : 1
  call_hooks record.send(@ar_timestamp), nil, [count] if count > 0 && @ar_scoped.exists?(record)
end

#last_update_atObject

Since:

  • 1.3.0



80
81
82
83
# File 'lib/vanity/metric/active_record.rb', line 80

def last_update_at
  record = @ar_scoped.find(:first, :order=>"#@ar_timestamp DESC", :limit=>1, :select=>@ar_timestamp)
  record && record.send(@ar_timestamp)
end

#track!(args = nil) ⇒ Object

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

Since:

  • 1.3.0



75
76
77
78
# File 'lib/vanity/metric/active_record.rb', line 75

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



59
60
61
62
63
64
65
66
67
68
69
70
71
72
# File 'lib/vanity/metric/active_record.rb', line 59

def values(sdate, edate)
  begin
    time = Time.now.in_time_zone
    difference = time.to_date - Date.today
    sdate = sdate + difference
    edate = edate + difference
  rescue NoMethodError #In Rails 2.3, if no time zone has been set this fails
  end
  query = { :conditions=> { @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 = @ar_column ? @ar_scoped.send(@ar_aggregate, @ar_column, query) : @ar_scoped.count(query)
  grouped = Hash[grouped.map {|k,v| [k.to_date, v] }]
  (sdate..edate).inject([]) { |ordered, date| ordered << (grouped[date] || 0) }
end