Class: RivetCms::ContentQuery

Inherits:
Object
  • Object
show all
Defined in:
app/services/rivet_cms/content_query.rb

Overview

Builds the published-document query for one content type: whitelisted sort, date-range filters, pagination clamp, and populate/fields validation. Shared by the delivery API controller and the Ruby content helpers so both access paths keep identical semantics.

Defined Under Namespace

Classes: Error

Constant Summary collapse

DEFAULT_PER_PAGE =
25
MAX_PER_PAGE =
100
DOCUMENT_SORTS =
{ "created_at" => :created_at, "updated_at" => :updated_at, "slug" => :slug }.freeze

Instance Method Summary collapse

Constructor Details

#initialize(content_type, sort: nil, filters: {}, page: nil, per_page: nil, populate: nil, fields: nil) ⇒ ContentQuery

Returns a new instance of ContentQuery.



13
14
15
16
17
18
19
20
21
# File 'app/services/rivet_cms/content_query.rb', line 13

def initialize(content_type, sort: nil, filters: {}, page: nil, per_page: nil, populate: nil, fields: nil)
  @content_type = content_type
  @sort = sort
  @filters = normalize_filters(filters)
  @page = page
  @per_page = per_page
  @populate = populate
  @fields = fields
end

Instance Method Details

#documentsObject

Kaminari page of published documents, ordered and filtered.



24
25
26
27
# File 'app/services/rivet_cms/content_query.rb', line 24

def documents
  base = @content_type.documents.where.not(published_revision_id: nil).includes(:published_revision)
  ordered(filtered(base)).page(@page).per(per_page)
end

#field_keysObject

Raises:



39
40
41
42
43
44
45
46
47
48
49
# File 'app/services/rivet_cms/content_query.rb', line 39

def field_keys
  return @field_keys if defined?(@field_keys)

  keys = normalize_list(@fields)
  return @field_keys = nil if keys.empty?

  unknown = keys - @content_type.fields.kept.pluck(:key)
  raise Error, "unknown field: #{unknown.first}" if unknown.any?

  @field_keys = keys
end

#populate_fieldsObject

Validated reference Field records to expand, already dropped when a fields selection excludes them so their targets are never preloaded.



31
32
33
34
35
36
37
# File 'app/services/rivet_cms/content_query.rb', line 31

def populate_fields
  @populate_fields ||= begin
    populate = resolve_populate
    keys = field_keys
    keys ? populate.select { |field| keys.include?(field.key) } : populate
  end
end