Sha256: 181fd23c099aad9d9e8eaf9cd9f02fec728274067828eeab03bb324aa405a1a2

Contents?: true

Size: 1.25 KB

Versions: 7

Compression:

Stored size: 1.25 KB

Contents

# frozen_string_literal: true

module Influxer
  # - Overriding loggging (use instrumentation and Rails logger)
  # - Add cache support for queries
  class Client
    def query(sql, options = {})
      log_sql(sql) do
        if !options.fetch(:cache, true) || Influxer.config.cache == false
          super(sql, options)
        else
          Rails.cache.fetch(normalized_cache_key(sql), cache_options(sql)) { super(sql, options) }
        end
      end
    end

    def log_sql(sql)
      return yield unless logger.debug?

      start_ts = Time.now
      res = yield
      duration = (Time.now - start_ts) * 1000

      name = "InfluxDB SQL (#{duration.round(1)}ms)"

      # bold black name and blue query string
      msg = "\e[1m\e[30m#{name}\e[0m  \e[34m#{sql}\e[0m"
      logger.debug msg
      res
    end

    # if sql contains 'now()' set expires to 1 minute or :cache_now_for value
    # of config.cache if defined
    def cache_options(sql = nil)
      options = Influxer.config.cache.dup
      options[:expires_in] = (options[:cache_now_for] || 60) if sql =~ /\snow\(\)/
      options
    end

    # add prefix; remove whitespaces
    def normalized_cache_key(sql)
      "influxer:#{sql.gsub(/\s*/, '')}"
    end

    def logger
      Rails.logger
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
influxer-1.1.6 lib/influxer/rails/client.rb
influxer-1.1.5 lib/influxer/rails/client.rb
influxer-1.1.4 lib/influxer/rails/client.rb
influxer-1.1.3 lib/influxer/rails/client.rb
influxer-1.1.2 lib/influxer/rails/client.rb
influxer-1.1.1 lib/influxer/rails/client.rb
influxer-1.1.0 lib/influxer/rails/client.rb