Sha256: 3cd65bffb7c38fc89e01ba3783cdb098f50f34cb8f5a8bec7969852e67cc5cf4

Contents?: true

Size: 1.13 KB

Versions: 2

Compression:

Stored size: 1.13 KB

Contents

# frozen_string_literal: true

require "csv"

module MrCommon
  # Renders collections of objects to a CSV string.
  #
  # @param collection [Enumerable<Object>] a collection of objects.
  # @param fields [Array<String, Symbol>] fields to use as columns in the CSV.
  #   It is expected that each item responds to each field if sent as a message.
  # @param decorator [SimpleDelegator, nil] optional wrapper class used to
  #   generate values for CSV rows when items in the collection don't respond to
  #   every field provided.
  class CSVRenderer
    attr_reader :collection, :decorator, :fields

    def initialize(collection: [], fields: [], decorator: nil)
      @collection = collection
      @decorator = decorator
      @fields = fields.map(&:to_sym)
    end

    # Renders the provided collection to a CSV string.
    #
    # @return [String] the CSV file contents
    def render
      CSV.generate do |csv|
        csv << fields

        collection.each do |item|
          item = decorator ? decorator.new(item) : item
          row = fields.map { |field_name| item.try(field_name) }
          csv << row
        end
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
mr_common-2.1.0 app/models/mr_common/csv_renderer.rb
mr_common-2.0.0 app/models/mr_common/csv_renderer.rb