Class: Shiboru::ParamParser

Inherits:
Object
  • Object
show all
Defined in:
lib/shiboru/param_parser.rb

Constant Summary collapse

RESERVED =
%w[ordering page page_size limit offset].freeze

Instance Method Summary collapse

Constructor Details

#initialize(params) ⇒ ParamParser

Returns a new instance of ParamParser.



7
8
9
# File 'lib/shiboru/param_parser.rb', line 7

def initialize(params)
  @raw = params.respond_to?(:to_unsafe_h) ? params.to_unsafe_h : params.to_h
end

Instance Method Details

#filtersObject



11
12
13
14
15
16
17
18
19
20
21
22
23
# File 'lib/shiboru/param_parser.rb', line 11

def filters
  @raw.each_with_object([]) do |(k, v), acc|
    next if RESERVED.include?(k.to_s)
    next if v.nil? || (v.respond_to?(:empty?) && v.empty?)

    path = k.to_s.split("__")
    op   = Shiboru::Operators::DEFAULT.key?(path.last) ? path.pop : "eq"
    field = path.pop
    assoc = path

    acc << { assoc: assoc, field: field, op: op, value: v }
  end
end

#orderingObject



25
26
27
# File 'lib/shiboru/param_parser.rb', line 25

def ordering
  (@raw["ordering"] || "").to_s.split(",").map(&:strip).reject(&:blank?)
end

#paginationObject



29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
# File 'lib/shiboru/param_parser.rb', line 29

def pagination
  if @raw.key?("page") || @raw.key?("page_size")
    {
      mode: :page,
      page: [@raw["page"].to_i, 1].max,
      page_size: clamp((@raw["page_size"] || @raw["limit"] || 25).to_i)
    }
  else
    {
      mode: :offset,
      limit: clamp((@raw["limit"] || 25).to_i),
      offset: [(@raw["offset"] || 0).to_i, 0].max
    }
  end
end