Sha256: c95f4907903ecfe3e6bdc34ef2b7cf8796a0af74c477ef0ccbe24f31f4ab7f73

Contents?: true

Size: 1008 Bytes

Versions: 2

Compression:

Stored size: 1008 Bytes

Contents

# frozen_string_literal: true

module QueryFilter
  module Utils
    # Usage:
    #
    #   range = Utils::ScopeRange.new(:orders, { orders_from: 1, orders_to: 44 })
    #   range.query('orders_count')
    #
    class ScopeRange
      def initialize(name, options = {})
        @name = name
        @options = options
      end

      def name_from
        @name_from ||= "#{@name}_from".to_sym
      end

      def name_to
        @name_to ||= "#{@name}_to".to_sym
      end

      def value_from
        @options[name_from]
      end

      def value_to
        @options[name_to]
      end

      def valid?
        @options && (value_from.present? || value_to.present?)
      end

      def query(column)
        if value_from.present? && value_to.present?
          ["#{column} BETWEEN ? AND ?", value_from, value_to]
        elsif value_from.present?
          ["#{column} >= ?", value_from]
        elsif value_to.present?
          ["#{column} <= ?", value_to]
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
query_filter-0.2.2 lib/query_filter/utils/scope_range.rb
query_filter-0.2.0 lib/query_filter/utils/scope_range.rb