Module: QueryTrace

Defined in:
lib/query_trace.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.append_features(klass) ⇒ Object



25
26
27
28
29
30
31
32
33
# File 'lib/query_trace.rb', line 25

def self.append_features(klass)
  super
  klass.class_eval do
    unless method_defined?(:log_without_trace)
      alias_method :log_without_trace, :log
      alias_method :log, :log_with_trace
    end
  end
end

.disable!Object



14
15
16
# File 'lib/query_trace.rb', line 14

def self.disable!
  @@trace_queries = false
end

.enable!Object



9
10
11
12
# File 'lib/query_trace.rb', line 9

def self.enable!
  ::ActiveRecord::ConnectionAdapters::AbstractAdapter.send(:include, QueryTrace) unless defined?(@@trace_queries)
  @@trace_queries = true
end

.enabled?Boolean

Returns:

  • (Boolean)


5
6
7
# File 'lib/query_trace.rb', line 5

def self.enabled?
  defined?(@@trace_queries) && @@trace_queries
end

.toggle!Object

Toggles query tracing on and off and returns a boolean indicating the new state of query tracing (true for enabled, false for disabled).



20
21
22
23
# File 'lib/query_trace.rb', line 20

def self.toggle!
  enabled? ? disable! : enable!
  enabled?
end

Instance Method Details

#format_trace(trace) ⇒ Object



48
49
50
51
52
53
54
55
# File 'lib/query_trace.rb', line 48

def format_trace(trace)
  if (defined?(ActiveRecord::LogSubscriber) ? ActiveRecord::LogSubscriber : ActiveRecord::Base).colorize_logging
    message_color = "35;2"
    trace.collect{|t| "    \e[#{message_color}m#{t}\e[0m"}.join("\n")
  else
    trace.join("\n    ")
  end
end

#log_with_trace(sql, name, &block) ⇒ Object



35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/query_trace.rb', line 35

def log_with_trace(sql, name, &block)
  result = log_without_trace(sql, name, &block)

  return result unless @@trace_queries

  return result unless ActiveRecord::Base.logger and ActiveRecord::Base.logger.debug?
  return result if / Columns$/ =~ name

  ActiveRecord::Base.logger.debug(format_trace(Rails.backtrace_cleaner.clean(caller)[0..self.depth]))

  result 
end