Class: JsonApiable::FilterParser

Inherits:
Object
  • Object
show all
Defined in:
lib/json_apiable/filter_parser.rb

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(filter_param, filter_class) ⇒ FilterParser

Returns a new instance of FilterParser.



11
12
13
14
# File 'lib/json_apiable/filter_parser.rb', line 11

def initialize(filter_param, filter_class)
  @filter_param = filter_param
  @filter_class = filter_class
end

Instance Attribute Details

#filter_classObject (readonly)

Returns the value of attribute filter_class.



9
10
11
# File 'lib/json_apiable/filter_parser.rb', line 9

def filter_class
  @filter_class
end

#filter_paramObject (readonly)

Returns the value of attribute filter_param.



9
10
11
# File 'lib/json_apiable/filter_parser.rb', line 9

def filter_param
  @filter_param
end

Class Method Details

.parse_filters!(jsonapi_build_params, filter_class) ⇒ Object



5
6
7
# File 'lib/json_apiable/filter_parser.rb', line 5

def self.parse_filters!(jsonapi_build_params, filter_class)
  FilterParser.new(jsonapi_build_params[:filter], filter_class).parse!
end

Instance Method Details

#parse!Object

Support filtering in the form of example.com/v1/posts?filter=draft,published



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/json_apiable/filter_parser.rb', line 17

def parse!
  raise_invalid_filter_class unless valid_filter_class?

  filter_hash = ActiveSupport::HashWithIndifferentAccess.new
  if valid_filter_query?
    filter_param.keys.each do |k|
      if valid_filter_key?(k)
        # support notation ?filter[param]=value1,value2,value3&...
        requested = filter_param[k].split(',')
        allowed_values = allowed_filter_keys[k]
        raise_invalid_filter_value(k) unless FilterMatchers.matches?(allowed_values, requested)

        filter_hash[k] = requested
      else
        raise_invalid_filter_value(k)
      end
    end
  elsif filter_param.present?
    raise ArgumentError, 'filter'
  end
  filter_hash
end