Class: ActiveRecordQueryCount::Tracker
- Inherits:
-
Object
- Object
- ActiveRecordQueryCount::Tracker
- Defined in:
- lib/active_record_query_count/recording/tracker.rb
Constant Summary collapse
- REGEX_TABLE_SQL =
/FROM\s+"(?<table>[^"]+)"/
Instance Attribute Summary collapse
-
#active_record_query_tracker ⇒ Object
Returns the value of attribute active_record_query_tracker.
-
#subscription ⇒ Object
Returns the value of attribute subscription.
Instance Method Summary collapse
-
#initialize ⇒ Tracker
constructor
A new instance of Tracker.
-
#reset_query_count ⇒ Object
This assums that in the same location of the code it will always be the same sql query.
- #subscribe ⇒ Object
- #unsubscribe ⇒ Object
Constructor Details
#initialize ⇒ Tracker
Returns a new instance of Tracker.
6 7 8 |
# File 'lib/active_record_query_count/recording/tracker.rb', line 6 def initialize reset_query_count end |
Instance Attribute Details
#active_record_query_tracker ⇒ Object
Returns the value of attribute active_record_query_tracker.
4 5 6 |
# File 'lib/active_record_query_count/recording/tracker.rb', line 4 def active_record_query_tracker @active_record_query_tracker end |
#subscription ⇒ Object
Returns the value of attribute subscription.
4 5 6 |
# File 'lib/active_record_query_count/recording/tracker.rb', line 4 def subscription @subscription end |
Instance Method Details
#reset_query_count ⇒ Object
This assums that in the same location of the code it will always be the same sql query
11 12 13 14 15 16 17 |
# File 'lib/active_record_query_count/recording/tracker.rb', line 11 def reset_query_count @active_record_query_tracker = Hash.new do |hash, key| hash[key] = { count: 0, location: Hash.new do |loc_hash, loc_key| loc_hash[loc_key] = { count: 0, sql: nil } end } end end |
#subscribe ⇒ Object
19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/active_record_query_count/recording/tracker.rb', line 19 def subscribe return unless subscription.nil? @subscription = ActiveSupport::Notifications.subscribe('sql.active_record') do |_a, start, finish, _d, payload| caller_from_sql = caller sql = payload[:sql] match = sql.match(REGEX_TABLE_SQL) if match.present? && match[:table] actual_location = Rails.backtrace_cleaner.clean(caller_from_sql).first active_record_query_tracker[match[:table]][:count] += 1 active_record_query_tracker[match[:table]][:location][actual_location][:duration] ||= 0 active_record_query_tracker[match[:table]][:location][actual_location][:duration] += (finish - start) * 1000 active_record_query_tracker[match[:table]][:location][actual_location][:count] += 1 active_record_query_tracker[match[:table]][:location][actual_location][:sql] = sql end end end |
#unsubscribe ⇒ Object
37 38 39 40 |
# File 'lib/active_record_query_count/recording/tracker.rb', line 37 def unsubscribe ActiveSupport::Notifications.unsubscribe(@subscription) @subscription = nil end |