Sha256: 4e3cc71b5e2d4de6ede69da3cd9a437a6dfbfc72d0f835cf64abb7b9f2ba60fe

Contents?: true

Size: 1.29 KB

Versions: 6

Compression:

Stored size: 1.29 KB

Contents

require_relative 'prepared_statement'
require 'active_support/core_ext/array/wrap'

module ActiveHouse
  module Whereable
    extend ActiveSupport::Concern

    included do
      private

      def format_condition(*conditions)
        raise ArgumentError, 'wrong number of arguments' if conditions.empty?
        return ActiveHouse::PreparedStatement.prepare_sql(*conditions) if conditions.size > 1
        condition = conditions.first
        if condition.is_a?(Hash)
          condition.map do |field, value|
            "#{field} #{sign_for_condition(value)} #{ActiveHouse::PreparedStatement.format_value(value)}"
          end
        else
          condition.to_s
        end
      end

      def sign_for_condition(value)
        if value.is_a?(Array)
          'IN'
        elsif value.nil?
          'IS'
        else
          '='
        end
      end

      def build_where_query_part
        "WHERE\n" + @conditions.join(" AND\n") unless @conditions.empty?
      end
    end

    def initialize(*)
      @conditions = []
      super
    end

    def where(*conditions)
      raise ArgumentError, 'wrong number of arguments' if conditions.empty?
      formatted_conditions = Array.wrap(format_condition(*conditions))
      chain_query conditions: (@conditions + formatted_conditions).uniq
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
active_house-0.3.2 lib/active_house/whereable.rb
active_house-0.3.1 lib/active_house/whereable.rb
active_house-0.3.0 lib/active_house/whereable.rb
active_house-0.2.2 lib/active_house/whereable.rb
active_house-0.2.1 lib/active_house/whereable.rb
active_house-0.2.0 lib/active_house/whereable.rb