Class: Serialism::Collection
- Inherits:
-
Object
- Object
- Serialism::Collection
- Defined in:
- lib/serialism/collection.rb
Overview
Combines a set of items and a serializer class.
Example:
class Foo
attr_accessor :id
end
class FooSerializer < Serialism::Serializer
attributes :id
end
Serialism::Collection.new(a_bunch_of_foo_instances, serializer: FooSerializer).to_csv
#=> returns a CSV string
Instance Attribute Summary collapse
-
#items ⇒ Object
Returns the value of attribute items.
Instance Method Summary collapse
-
#attributes ⇒ Array
return the attributes for the collection.
-
#initialize(items = [], serializer:) ⇒ Collection
constructor
create a new collection.
-
#to_a ⇒ Object
this generates an array of arrays headers are [0] data starts at [1].
-
#to_csv ⇒ String
Generate a csv string for the collection.
- #to_json ⇒ Object
Constructor Details
#initialize(items = [], serializer:) ⇒ Collection
create a new collection
26 27 28 29 30 31 32 33 34 35 36 |
# File 'lib/serialism/collection.rb', line 26 def initialize(items = [], serializer:) if !serializer.respond_to?(:attributes) raise ArgumentError, 'serializer must implement a class-level :attributes method' end if !serializer.instance_methods.include?(:render) raise ArgumentError, 'serializer must implement an instance-level :render method' end @serializer = serializer self.items = items end |
Instance Attribute Details
#items ⇒ Object
Returns the value of attribute items.
17 18 19 |
# File 'lib/serialism/collection.rb', line 17 def items @items end |
Instance Method Details
#attributes ⇒ Array
return the attributes for the collection
55 56 57 58 59 |
# File 'lib/serialism/collection.rb', line 55 def attributes return [] if items.empty? @serializer.attributes end |
#to_a ⇒ Object
this generates an array of arrays headers are [0] data starts at [1]
87 88 89 |
# File 'lib/serialism/collection.rb', line 87 def to_a [attributes] + items.map { |i| render_row(i) } end |
#to_csv ⇒ String
Generate a csv string for the collection
When members of the array returned by the serializer are themselves arrays, these sub-arrays will be joined using “,” prior to being added to the main CSV.
68 69 70 71 72 73 74 75 76 77 |
# File 'lib/serialism/collection.rb', line 68 def to_csv require 'csv' CSV.generate do |csv| csv << attributes items.map do |i| csv << render_row(i) end end end |
#to_json ⇒ Object
79 80 81 82 83 |
# File 'lib/serialism/collection.rb', line 79 def to_json require 'json' JSON.dump(items.map { |t| @serializer.new(t).render }) end |