Sha256: 7187ef91e286104c0fea3cde05ca8eccc31c6eba1ad524743108bb16a3bde6c7

Contents?: true

Size: 1.69 KB

Versions: 11

Compression:

Stored size: 1.69 KB

Contents

# frozen_string_literal: true

module IronBank
  # A query builder helps buidling a syntaxically correct query using ZOQL.
  #
  class QueryBuilder
    private_class_method :new

    def self.zoql(object, fields, conditions = {})
      new(object, fields, conditions).zoql
    end

    def zoql
      query = "select #{query_fields} from #{object}"
      conditions.empty? ? query : "#{query} where #{query_conditions}"
    end

    private

    attr_reader :object, :fields, :conditions

    def initialize(object, fields, conditions)
      @object     = object
      @fields     = fields
      @conditions = conditions
    end

    def query_fields
      fields.join(',')
    end

    def query_conditions
      ensure_range_single_condition

      case conditions
      when Hash
        hash_query_conditions
      end
    end

    def range_query_builder(field, value)
      value.each.with_object([]) do |option, range_query|
        range_query << "#{field}='#{option}'"
      end.join(' OR ')
    end

    def hash_query_conditions
      conditions.each.with_object([]) do |(field, value), filters|
        # TODO: sanitize the value
        field = IronBank::Utils.camelize(field)
        filters << current_filter(field, value)
      end.join(' AND ')
    end

    def current_filter(field, value)
      if value.is_a?(Array)
        range_query_builder(field, value)
      elsif [true, false].include? value
        "#{field}=#{value}"
      else
        "#{field}='#{value}'"
      end
    end

    def ensure_range_single_condition
      return if conditions.count <= 1
      return unless conditions.values.any? { |value| value.is_a?(Array) }

      raise 'Filter ranges must be used in isolation.'
    end
  end
end

Version data entries

11 entries across 11 versions & 1 rubygems

Version Path
iron_bank-2.2.0 lib/iron_bank/query_builder.rb
iron_bank-2.1.0 lib/iron_bank/query_builder.rb
iron_bank-2.0.2 lib/iron_bank/query_builder.rb
iron_bank-2.0.1 lib/iron_bank/query_builder.rb
iron_bank-2.0.0 lib/iron_bank/query_builder.rb
iron_bank-1.0.4 lib/iron_bank/query_builder.rb
iron_bank-1.0.3 lib/iron_bank/query_builder.rb
iron_bank-1.0.2 lib/iron_bank/query_builder.rb
iron_bank-1.0.1 lib/iron_bank/query_builder.rb
iron_bank-1.0.0 lib/iron_bank/query_builder.rb
iron_bank-0.7.1 lib/iron_bank/query_builder.rb