Class: Jsonapi::QueryBuilder::BaseQuery

Inherits:
Object
  • Object
show all
Includes:
Mixins::Filter, Mixins::Include, Mixins::Paginate, Mixins::Sort
Defined in:
lib/jsonapi/query_builder/base_query.rb

Instance Attribute Summary collapse

Attributes included from Mixins::Paginate

#pagination_details

Instance Method Summary collapse

Methods included from Mixins::Sort

#sort

Methods included from Mixins::Paginate

#paginate

Methods included from Mixins::Include

#add_includes

Methods included from Mixins::Filter

#filter

Constructor Details

#initialize(collection, params) ⇒ BaseQuery

Returns a new instance of BaseQuery.

Parameters:

  • collection (ActiveRecord::Relation)
  • params (Hash)

    Json:Api query parameters



22
23
24
25
# File 'lib/jsonapi/query_builder/base_query.rb', line 22

def initialize(collection, params)
  @collection = collection
  @params = params.deep_symbolize_keys
end

Instance Attribute Details

#collectionObject

Returns the value of attribute collection.



18
19
20
# File 'lib/jsonapi/query_builder/base_query.rb', line 18

def collection
  @collection
end

#paramsObject

Returns the value of attribute params.



18
19
20
# File 'lib/jsonapi/query_builder/base_query.rb', line 18

def params
  @params
end

Instance Method Details

#find(id) ⇒ Object

Parameters:

  • id (integer, string)

Returns:

  • (Object)

Raises:

  • (ActiveRecord::RecordNotFound)

    if the record by the id is not found



41
42
43
# File 'lib/jsonapi/query_builder/base_query.rb', line 41

def find(id)
  find_by! id: id
end

#find_by!(**kwargs) ⇒ Object

Parameters:

  • kwargs (Hash)

    Attributes with required values

Returns:

  • (Object)

Raises:

  • (ActiveRecord::RecordNotFound)

    if the record by the arguments is not found



55
56
57
# File 'lib/jsonapi/query_builder/base_query.rb', line 55

def find_by!(**kwargs)
  add_includes(collection).find_by!(kwargs)
end

#recordObject

Finds the record by the id parameter the class is instantiated with

Returns:

  • (Object)

Raises:

  • (ActiveRecord::RecordNotFound)

    if the record by the id is not found



48
49
50
# File 'lib/jsonapi/query_builder/base_query.rb', line 48

def record
  find_by! id: params[:id]
end

#resultsActiveRecord::Relation

Note:

Pagination details are saved to an instance variable and can be accessed via the #pagination_details attribute reader

Returns A collection with eager loaded relationships based on include params, filtered, ordered and lastly, paginated.

Returns:

  • (ActiveRecord::Relation)

    A collection with eager loaded relationships based on include params, filtered, ordered and lastly, paginated.



30
31
32
33
34
35
36
# File 'lib/jsonapi/query_builder/base_query.rb', line 30

def results
  collection
    .yield_self(&method(:add_includes))
    .yield_self(&method(:sort))
    .yield_self(&method(:filter))
    .yield_self(&method(:paginate))
end