Class: Filterameter::QueryBuilder

Inherits:
Object
  • Object
show all
Defined in:
lib/filterameter/query_builder.rb

Overview

# Query Builder

Class Query Builder turns filter parameters into a query.

The query builder is instantiated by the filter coordinator. The default query currently is simple all. The default sort comes for the controller declaration of the same name; it is optional and the value may be nil.

If the request includes a sort, it is always applied. If not, the following logic kicks in to provide a sort:

  • if the starting query includes a sort, no additional sort is applied

  • if a default sort has been declared, it is applied

  • if neither of those provides a sort, then the fallback is primary key desc

Instance Method Summary collapse

Constructor Details

#initialize(default_query, default_sort, filter_registry) ⇒ QueryBuilder

Returns a new instance of QueryBuilder.



17
18
19
20
21
# File 'lib/filterameter/query_builder.rb', line 17

def initialize(default_query, default_sort, filter_registry)
  @default_query = default_query
  @default_sort = default_sort
  @registry = filter_registry
end

Instance Method Details

#build_query(filter_params, starting_query = nil) ⇒ Object



23
24
25
26
27
# File 'lib/filterameter/query_builder.rb', line 23

def build_query(filter_params, starting_query = nil)
  sorts, filters = parse_filter_params(filter_params.stringify_keys)
  query = apply_filters(starting_query || @default_query, filters)
  apply_sorts(query, sorts)
end