Sha256: 0f18f1a7bd8fdfd3e7272e391dfc810c9ae94d00fb6515bd1c0030a998d20c7c

Contents?: true

Size: 1.69 KB

Versions: 7

Compression:

Stored size: 1.69 KB

Contents

# frozen_string_literal: true

module Wayfarer
  module Routing
    module Matchers
      Query = Struct.new(:fields) do
        def match(url)
          query = url.query

          # CGI::parse throws a NoMethodError if the query is an empty string
          return false if query.nil? || query.empty?

          CGI.parse(query).none? { |field, vals| violates?(field, vals) }
        end

        def params(url)
          return {} unless match(url)

          CGI.parse(url.query)
             .select { |(k, _)| fields.keys.include?(k.to_sym) }
             .transform_values(&:last)
        end

      private

        # rubocop:disable Lint/AssignmentInCondition
        def violates?(field, vals)
          return false unless constraint = fields[field.to_sym]

          violates_constraint?(constraint, vals)
        end
        # rubocop:enable Lint/AssignmentInCondition

        def violates_constraint?(constraint, vals)
          case constraint
          when String  then violates_string?(constraint, vals)
          when Integer then violates_integer?(constraint, vals)
          when Regexp  then violates_regexp?(constraint, vals)
          when Range   then violates_range?(constraint, vals)
          end
        end

        def violates_string?(str, vals)
          vals.none? { |val| str == val }
        end

        def violates_integer?(int, vals)
          vals.none? { |val| int == Integer(val) }
        rescue ArgumentError
          true
        end

        def violates_regexp?(regexp, vals)
          vals.none? { |val| regexp.match(val) }
        end

        def violates_range?(range, vals)
          vals.none? { |val| range.include?(val.to_i) }
        end
      end
    end
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
wayfarer-0.4.7 lib/wayfarer/routing/matchers/query.rb
wayfarer-0.4.6 lib/wayfarer/routing/matchers/query.rb
wayfarer-0.4.5 lib/wayfarer/routing/matchers/query.rb
wayfarer-0.4.4 lib/wayfarer/routing/matchers/query.rb
wayfarer-0.4.3 lib/wayfarer/routing/matchers/query.rb
wayfarer-0.4.2 lib/wayfarer/routing/matchers/query.rb
wayfarer-0.4.1 lib/wayfarer/routing/matchers/query.rb