Sha256: ed4b7d27c6703820182492bbc6d2b0c1c9b129660b6351ccaa44e73933d1e9f5

Contents?: true

Size: 1.27 KB

Versions: 5

Compression:

Stored size: 1.27 KB

Contents

# Define filter rules
#
module QueryFilter
  module Rules
    class Scope
      VALIDATON_KEYS = [:in, :only, :format, :if, :unless].freeze

      attr_reader :keys

      def initialize(keys, options = {})
        @keys = Array(keys)
        @options = options
      end

      def blank_validation?
        (@options.keys & VALIDATON_KEYS).empty?
      end

      def valid?(params)
        values = normalize_params(params)

        checks = []
        checks << @options[:in].include?(values.first) if @options[:in]
        checks << @options[:only].include?(values.first) if @options[:only]
        checks << !values.map(&:blank?).all? if blank_validation?
        checks << @options[:intersect] & Array.wrap(values) if @options[:intersect]

        !checks.empty? && checks.all?
      end

      def endpoint
        @options[:to] || "#{name}_#{key}"
      end

      def name
        'scope'.freeze
      end

      def key
        @key ||= @keys.first
      end

      def normalize_params(params)
        params.values_at(*keys)
      end

      def can_apply?(target)
        conditions = QueryFilter::Utils::UserConditions.new(target, @options)

        if conditions.present?
          conditions.passed?
        else
          valid?(target.params)
        end
      end
    end
  end
end

Version data entries

5 entries across 5 versions & 1 rubygems

Version Path
query_filter-0.1.8 lib/query_filter/rules/scope.rb
query_filter-0.1.7 lib/query_filter/rules/scope.rb
query_filter-0.1.6 lib/query_filter/rules/scope.rb
query_filter-0.1.5 lib/query_filter/rules/scope.rb
query_filter-0.1.4 lib/query_filter/rules/scope.rb