File: builder.rb

package info (click to toggle)
ruby-influxdb 0.8.1-2
  • links: PTS, VCS
  • area: main
  • in suites: bookworm
  • size: 424 kB
  • sloc: ruby: 3,530; sh: 61; makefile: 7
file content (43 lines) | stat: -rw-r--r-- 1,165 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
module InfluxDB
  module Query # :nodoc: all
    class Builder
      def build(query, params)
        case params
        when Array    then params = params_from_array(params)
        when Hash     then params = params_from_hash(params)
        when NilClass then params = {}
        else raise ArgumentError, "Unsupported #{params.class} params"
        end

        query % params
      rescue KeyError => e
        raise ArgumentError, e.message
      end

      def quote(param)
        case param
        when String, Symbol
          "'".freeze + param.to_s.gsub(/['"\\\x0]/, '\\\\\0') + "'".freeze
        when Integer, Float, TrueClass, FalseClass
          param.to_s
        else
          raise ArgumentError, "Unexpected parameter type #{param.class} (#{param.inspect})"
        end
      end

      private

      def params_from_hash(params)
        params.each_with_object({}) do |(k, v), hash|
          hash[k.to_sym] = quote(v)
        end
      end

      def params_from_array(params)
        params.each_with_object({}).with_index do |(param, hash), i|
          hash[(i + 1).to_s.to_sym] = quote(param)
        end
      end
    end
  end
end