class JsonApiServer::FilterParser
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.
Attributes
attr[R]
The filter name, i.e., :id, :title
casted_value[R]
Original value cast to the appropriate data type.
config[R]
Instance of FilterConfig
for the filter.
model[R]
Model class or ActiveRecord_Relation. Queries are built using this model.
operator[R]
Query operator if one applies. i.e., IN, =, <, >, >=, <=, !=
value[R]
The original filter value.
Public Class Methods
new(attr, value, model, config)
click to toggle source
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.
# 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
Public Instance Methods
to_query()
click to toggle source
Converts filter into an ActiveRecord::Relation where query which can be merged with other queries.
# 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
Protected Instance Methods
builder_key()
click to toggle source
# File lib/json_api_server/filter_parser.rb, line 49 def builder_key return config.builder if config.builder.present? case operator when 'IN' config.in || configuration.default_in_builder when '*' config.like || configuration.default_like_builder when *SqlComp.allowed_operators config.comparison || configuration.default_comparison_builder else config.default || configuration.default_builder end end
cast(value, type)
click to toggle source
# File lib/json_api_server/filter_parser.rb, line 80 def cast(value, type) JsonApiServer::Cast.to(value, type) end
configuration()
click to toggle source
# File lib/json_api_server/filter_parser.rb, line 84 def configuration JsonApiServer.configuration end
parse()
click to toggle source
Value, operator, or specified class.
# File lib/json_api_server/filter_parser.rb, line 65 def parse if value.include?(',') arr = value.split(',') arr.map!(&:strip) @casted_value = cast(arr, config.type) @operator = 'IN' else value =~ /\A(!?[<|>]?=?\*?)(.+)/ # JsonApiServer.logger.debug("VALUE IS #{Regexp.last_match(2)}") # JsonApiServer.logger.debug("CONFIG.TYPE IS #{config.type}") @casted_value = cast(Regexp.last_match(2), config.type) @operator = Regexp.last_match(1) end end