Class: Dooly::Collection::Base

Inherits:
Object
  • Object
show all
Extended by:
Forwardable
Includes:
ActiveModel::Serializers::JSON, Attachment
Defined in:
lib/dooly/collection/base.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Methods included from Attachment

#attachment

Constructor Details

#initialize(*args) ⇒ Base

Returns a new instance of Base.



16
17
18
19
20
21
# File 'lib/dooly/collection/base.rb', line 16

def initialize(*args)
  if args.first.respond_to?(:each)
    args = args.first
  end
  @collection = args
end

Instance Attribute Details

#collectionObject (readonly)

Returns the value of attribute collection.



12
13
14
# File 'lib/dooly/collection/base.rb', line 12

def collection
  @collection
end

Instance Method Details

#as_json(options = {}) ⇒ Object



23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
# File 'lib/dooly/collection/base.rb', line 23

def as_json(options = {})
  root = options.delete(:root) || self.include_root_in_json
  jsons = block_given? ? self.as_jsons(options, &Proc.new) : self.as_jsons(options)
  if root
    if root == true
      root = begin 
          @collection[0].class.model_name.element.pluralize
        rescue
          self.class.name.underscore.split('/')[-2].pluralize rescue 'collection'
        end
    end
    {root => jsons}
  else
    jsons
  end
end

#as_jsons(options = {}) ⇒ Object



40
41
42
43
44
45
46
47
48
# File 'lib/dooly/collection/base.rb', line 40

def as_jsons(options = {})
  @collection.map do |member|
    if block_given?
      member.as_json(options, &Proc.new)
    else
      member.as_json(options)
    end
  end
end