Bobochka
6/16/2015 - 7:24 AM

ActiveRecord print caller

ActiveRecord print caller

module ActiveRecord
  module ConnectionAdapters
    class Mysql2Adapter < AbstractMysqlAdapter
      def execute(sql, name = nil)
        @connection.query_options[:database_timezone] = ActiveRecord::Base.default_timezone
        if name == :skip_logging
          @connection.query(sql)
        else
          # caller logging
          log_stack
          # EO
          log(sql, name) { @connection.query(sql) }
        end
      rescue ActiveRecord::StatementInvalid => exception
        if exception.message.split(":").first =~ /Packets out of order/
          raise ActiveRecord::StatementInvalid, "'Packets out of order'... bindings."
        else
          raise
        end
      end

      private

      def log_stack
        #If marazmuz will take over i would not like to spam logs in production
        return unless Rails.env == 'development'
        #Regex with rails directory path would be helpful in taking app stack trace only
        regexp = Regexp.new( Rails.root.to_s )
        res = ''
        caller.each_with_index{|x,i|
          #We'll took only items containing Rails.root and we are not interested in current stack position, so skip i == 0
          res << "#{ '#'+i.to_s}:\t#{ x.sub(regexp,'') }\n" if x =~ regexp && i != 0
        }
        p ( res ) unless res.blank?

      end

    end
  end
end