Class: CafeCar::ParamParser

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

Instance Method Summary collapse

Constructor Details

#initialize(params) ⇒ ParamParser

Returns a new instance of ParamParser.



2
3
4
# File 'lib/cafe_car/param_parser.rb', line 2

def initialize(params)
  @params = params
end

Instance Method Details

#merge(_, a, b) ⇒ Object



17
18
19
20
21
22
23
# File 'lib/cafe_car/param_parser.rb', line 17

def merge(_, a, b)
  if a.is_a?(Array) || b.is_a?(Array)
    [ *Array.wrap(a), *Array.wrap(b) ]
  else
    b
  end
end

#params(params) ⇒ Object



11
12
13
14
15
# File 'lib/cafe_car/param_parser.rb', line 11

def params(params)
  params.map { |k, v| k.split(".").reverse.reduce(value(v)) { { _2 => _1 } } }
        .reduce({}) { _1.deep_merge(_2, &method(:merge)) }
        .with_indifferent_access
end

#parsedObject



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

def parsed
  @parsed ||= @params.compact_blank
                     .then { params _1 }
end

#value(v) ⇒ Object



25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
# File 'lib/cafe_car/param_parser.rb', line 25

def value(v)
  case v
  when Array      then v.map { value(_1) }
  when Hash       then params(v).tap { _1.merge!(_1.delete("")) if _1[""] }
  when '""', "''" then ""
  when "nil", ""  then nil
  when /[{}\[\]]/ then value(JSON.parse(v))
  when /,/        then value(v.split(","))
  when /^(.*?)\.\.(\.?)(.*)$/
    begin
      Range.new(value($1), value($3), $2.present?)
    rescue ArgumentError
      v
    end
  when /^\$(\w+)\.(\w+)$/
    # TODO: make less scary
    $1.constantize.arel_table[$2]
  else v
  end
end