Class: Wayfarer::Routing::Matchers::Query

Inherits:
Object
  • Object
show all
Defined in:
lib/wayfarer/routing/matchers/query.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(fields) ⇒ Query

Returns a new instance of Query.



9
10
11
# File 'lib/wayfarer/routing/matchers/query.rb', line 9

def initialize(fields)
  @fields = fields
end

Instance Attribute Details

#fieldsObject (readonly)

Returns the value of attribute fields.



7
8
9
# File 'lib/wayfarer/routing/matchers/query.rb', line 7

def fields
  @fields
end

Instance Method Details

#evaluate(path_finder) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/wayfarer/routing/matchers/query.rb', line 13

def evaluate(path_finder)
  query = path_finder.uri.query

  return false if query.nil? || query.empty?

  # TODO: Move query parameter parsing to PathFinder
  parsed_query = CGI.parse(query)

  # For every expected field in `fields`,
  # check that it is present and does not violate the constraint.
  fields.all? do |(field_key, constraint)|
    param_vals = parsed_query[field_key.to_s]

    # If the param is absent, mismatch
    if param_vals.nil? || param_vals.empty?
      false
    else
      !violates_constraint?(constraint, param_vals)
    end
  end
end

#params(path_finder) ⇒ Object



35
36
37
38
39
40
41
42
43
# File 'lib/wayfarer/routing/matchers/query.rb', line 35

def params(path_finder)
  return {} unless evaluate(path_finder)

  parsed_query = CGI.parse(path_finder.uri.query)

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

#to_hObject



45
46
47
48
49
50
51
52
53
# File 'lib/wayfarer/routing/matchers/query.rb', line 45

def to_h
  fields.transform_values do |val|
    case val
    when Regexp then val.inspect
    when Range then { min: val.min, max: val.max }
    else val
    end
  end
end