lib/serialism/collection.rb in serialism-0.0.1 vs lib/serialism/collection.rb in serialism-0.2.0

- old
+ new

@@ -1,7 +1,6 @@ module Serialism - # Combines a set of items and a serializer class. # # Example: # # class Foo @@ -13,26 +12,25 @@ # end # # Serialism::Collection.new(a_bunch_of_foo_instances, serializer: FooSerializer).to_csv # #=> returns a CSV string class Collection - attr_reader :items # create a new collection # - # @param[Enumerable] items + # @param [Enumerable] items # A collection of items. # All member items should be encodable by `serializer`. - # @param[Serialism::Serializer] serializer + # @param [Serialism::Serializer] serializer # The serializer class used to encode members of `items`. - def initialize(items=[], serializer:) - if ! serializer.respond_to?(:attributes) - raise ArgumentError, "serializer must implement a class-level :attributes method" + 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" + if !serializer.instance_methods.include?(:render) + raise ArgumentError, 'serializer must implement an instance-level :render method' end @serializer = serializer self.items = items end @@ -40,24 +38,24 @@ # Set the items in the collection. # # Replaces any previous items already in the collection. # # @param [#each] items an enumerable collection of items - # @return [CsvCollection] + # @return [Serialism::Collection] def items=(items) - raise ArgumentError, "argument must respond_to :each" if ! items.respond_to?(:each) - raise ArgumentError, "argument must respond_to :map" if ! items.respond_to?(:map) + raise ArgumentError, 'argument must respond_to :each' if !items.respond_to?(:each) + raise ArgumentError, 'argument must respond_to :map' if !items.respond_to?(:map) @items = items self end # return the attributes for the collection # # @return [Array] def attributes - return [] if items.size == 0 + return [] if items.empty? @serializer.attributes end # Generate a csv string for the collection @@ -70,25 +68,32 @@ def to_csv require 'csv' CSV.generate do |csv| csv << attributes - items.each do |t| - - row = @serializer.new(t).render.values.map do |cell| - # convert complex cells to comma-separated strings - cell.is_a?(Array) ? cell.join(',') : cell - end - - csv << row + items.map do |i| + csv << render_row(i) end end end def to_json require 'json' - JSON.dump(items.map {|t| @serializer.new(t).render }) + JSON.dump(items.map { |t| @serializer.new(t).render }) end + # this generates an array of arrays + # headers are [0] data starts at [1] + def to_a + [attributes] + items.map { |i| render_row(i) } + end + + private + + def render_row(row) + @serializer.new(row).render.values.map do |cell| + cell.is_a?(Array) ? cell.join(',') : cell + end + end end end