Class: JsonApiServer::FilterParser

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

Overview

Takes a filter param and associated config and creates an ActiveRecord::Relation query which can be merged into a master query. Part of jsonapi.org/recommendations/#filtering.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(attr, value, model, config) ⇒ FilterParser

parameters:

- attr (String) - filter name as it appears in the url.
                 i.e., filter[tags]=art,theater => tags
- value (String) - value from query, i.e., 'art,theater'
- model (class or class name) - Model class or class name.
                 i.e., User or 'User'.
- config (instance of FilterConfig) - filter config for the filter.


30
31
32
33
34
35
36
# File 'lib/json_api_server/filter_parser.rb', line 30

def initialize(attr, value, model, config)
  @attr = attr
  @value = value
  @model = model.is_a?(Class) ? model : model.constantize
  @config = config
  parse
end

Instance Attribute Details

#attrObject (readonly)

The filter name, i.e., :id, :title



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

def attr
  @attr
end

#casted_valueObject (readonly)

Original value cast to the appropriate data type.



15
16
17
# File 'lib/json_api_server/filter_parser.rb', line 15

def casted_value
  @casted_value
end

#configObject (readonly)

Instance of FilterConfig for the filter.



19
20
21
# File 'lib/json_api_server/filter_parser.rb', line 19

def config
  @config
end

#modelObject (readonly)

Model class or ActiveRecord_Relation. Queries are built using this model.



17
18
19
# File 'lib/json_api_server/filter_parser.rb', line 17

def model
  @model
end

#operatorObject (readonly)

Query operator if one applies. i.e., IN, =, <, >, >=, <=, !=



21
22
23
# File 'lib/json_api_server/filter_parser.rb', line 21

def operator
  @operator
end

#valueObject (readonly)

The original filter value.



13
14
15
# File 'lib/json_api_server/filter_parser.rb', line 13

def value
  @value
end

Instance Method Details

#to_queryObject

Converts filter into an ActiveRecord::Relation where query which can be merged with other queries.



40
41
42
43
44
45
# File 'lib/json_api_server/filter_parser.rb', line 40

def to_query
  return nil if config.nil? # not a whitelisted attr
  klass = JsonApiServer.filter_builder(builder_key) || raise("Query builder '#{builder_key}' doesn't exist.")
  builder = klass.new(attr, casted_value, operator, config)
  builder.to_query(@model)
end