Sha256: 6d964904851bab0e12c830ef5d7c95820d7db30521372010a08e66c697530d37

Contents?: true

Size: 1.44 KB

Versions: 1

Compression:

Stored size: 1.44 KB

Contents

require 'yap/extended_range'

module Yap
  class Filter < Hash
    def initialize
      self[:where] = {}
      self[:not] = {}
    end

    def parse!(column, values)
      values.to_s.split(',').each do |value|
        # Perform negative match if value starts with '!'.
        if value =~/^!(.+)$/
          match = :not
          value = $1
        else
          match = :where
        end

        case value
        when /([<>]=?)(.+)/
          match, value = handle_comparison_operators(match, column, $1.to_sym, $2)
        when /(.+)\.{3}(.+)/
          value = $1...$2
        when /(.+)\.{2}(.+)/
          value = $1..$2
        else
          # Convert null to ruby nil to use 'IS NULL' in SQL.
          value = value.downcase == 'null' ? nil : value
        end

        # Ensure filter contains an array to append to.
        self[match][column] ||= []

        self[match][column] << value
      end
    end

    private

    def handle_comparison_operators(match, column, operator, value)
      case operator
      when :<
        handle_comparison_operators(toggle_match(match), column, :>=, value)
      when :>
        handle_comparison_operators(toggle_match(match), column, :<=, value)
      when :<=
        return match, ExtendedRange.new(-String::INFINITY, value)
      when :>=
        return match, ExtendedRange.new(value, String::INFINITY)
      end
    end

    def toggle_match(match)
      match == :where ? :not : :where
    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
yap-1.4.0 lib/yap/filter.rb