Class: MrCommon::CSVRenderer
- Inherits:
-
Object
- Object
- MrCommon::CSVRenderer
- Defined in:
- app/models/mr_common/csv_renderer.rb
Overview
Renders collections of objects to a CSV string.
Instance Attribute Summary collapse
-
#collection ⇒ Object
readonly
Returns the value of attribute collection.
-
#decorator ⇒ Object
readonly
Returns the value of attribute decorator.
-
#fields ⇒ Object
readonly
Returns the value of attribute fields.
Instance Method Summary collapse
-
#initialize(collection: [], fields: [], decorator: nil) ⇒ CSVRenderer
constructor
A new instance of CSVRenderer.
-
#render ⇒ String
Renders the provided collection to a CSV string.
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
#collection ⇒ Object (readonly)
Returns the value of attribute collection.
15 16 17 |
# File 'app/models/mr_common/csv_renderer.rb', line 15 def collection @collection end |
#decorator ⇒ Object (readonly)
Returns the value of attribute decorator.
15 16 17 |
# File 'app/models/mr_common/csv_renderer.rb', line 15 def decorator @decorator end |
#fields ⇒ Object (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
#render ⇒ String
Renders the provided collection to a CSV string.
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 |