Class: CrudMuffins::Rails::Adapter::Collection

Inherits:
Object
  • Object
show all
Defined in:
lib/crud-muffins-rails.rb

Overview

Chainable, immutable PORO that encapsulates an ActiveRecord::Collection, but can delegate ‘as_json` to map the records through the provided adapter.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(collection, adapter) ⇒ Collection

Returns a new instance of Collection.



25
26
27
28
# File 'lib/crud-muffins-rails.rb', line 25

def initialize(collection, adapter)
  @collection = collection
  @adapter = adapter
end

Instance Attribute Details

#adapterObject (readonly)

Returns the value of attribute adapter.



22
23
24
# File 'lib/crud-muffins-rails.rb', line 22

def adapter
  @adapter
end

#collectionObject (readonly)

Returns the value of attribute collection.



22
23
24
# File 'lib/crud-muffins-rails.rb', line 22

def collection
  @collection
end

Instance Method Details

#+(other) ⇒ Object



50
51
52
53
# File 'lib/crud-muffins-rails.rb', line 50

def +(other)
  @collection = collection + other.collection
  self
end

#as_jsonObject



55
56
57
58
59
60
61
62
63
64
65
66
67
68
# File 'lib/crud-muffins-rails.rb', line 55

def as_json(*)
  json = {
    data: collection.map { |obj| adapter.new(obj) },
  }

  if collection.respond_to?(:previous_page)
    json[:pagination] = {
      previous: collection&.previous_page,
      next: collection&.next_page
    }
  end

  json
end

#limit(*args) ⇒ Object



45
46
47
48
# File 'lib/crud-muffins-rails.rb', line 45

def limit(*args)
  @collection = collection.limit(*args)
  self
end

#order(*args) ⇒ Object



35
36
37
38
# File 'lib/crud-muffins-rails.rb', line 35

def order(*args)
  @collection = collection.order(*args)
  self
end

#paginate(*args) ⇒ Object



40
41
42
43
# File 'lib/crud-muffins-rails.rb', line 40

def paginate(*args)
  @collection = collection.paginate(*args)
  self
end

#where(*args) ⇒ Object



30
31
32
33
# File 'lib/crud-muffins-rails.rb', line 30

def where(*args)
  @collection = collection.where(*args)
  self
end