Class: MrCommon::CSVRenderer

Inherits:
Object
  • Object
show all
Defined in:
app/models/mr_common/csv_renderer.rb

Overview

Renders collections of objects to a CSV string.

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(collection: [], fields: [], decorator: nil) ⇒ CSVRenderer

Returns a new instance of CSVRenderer.



17
18
19
20
21
# File 'app/models/mr_common/csv_renderer.rb', line 17

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

Instance Attribute Details

#collectionObject (readonly)

Returns the value of attribute collection.



15
16
17
# File 'app/models/mr_common/csv_renderer.rb', line 15

def collection
  @collection
end

#decoratorObject (readonly)

Returns the value of attribute decorator.



15
16
17
# File 'app/models/mr_common/csv_renderer.rb', line 15

def decorator
  @decorator
end

#fieldsObject (readonly)

Returns the value of attribute fields.



15
16
17
# File 'app/models/mr_common/csv_renderer.rb', line 15

def fields
  @fields
end

Instance Method Details

#renderString

Renders the provided collection to a CSV string.

Returns:

  • (String)

    the CSV file contents



26
27
28
29
30
31
32
33
34
35
36
# File 'app/models/mr_common/csv_renderer.rb', line 26

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