Class: EasyExport::Exporter
- Inherits:
-
Object
- Object
- EasyExport::Exporter
- Defined in:
- lib/easy_export.rb
Instance Method Summary collapse
- #data ⇒ Object
- #file_name ⇒ Object
- #file_type ⇒ Object
-
#initialize(options = {}) ⇒ Exporter
constructor
Instantiate an Exporter that will convert a collection of models into a CSV string.
Constructor Details
#initialize(options = {}) ⇒ Exporter
Instantiate an Exporter that will convert a collection of models into a CSV string. The model needs to be setup with ‘exportable` class method.
@options:
model: string name of the model class used to fetch instances to convert.
filter: a string that can be used by the @scope to further filter models
...any other args needed in the passed to the @scope.
@model: the model class. @scope: a proc or object that responds to #call and takes the @options hash
and returns a scoped collection of instances of @model.
@fields: an array of 2 element arrays that represent the header and method
to call on the model to retrieve the value for that column.
@header: the first element of every array in @fields
81 82 83 84 85 86 87 88 89 |
# File 'lib/easy_export.rb', line 81 def initialize( = {}) = @model = [:model].constantize # the @model.export_scope is configured via the `exportable` block @scope = .fetch :scope, @model.export_scope # the fields configured via the `exportable` block @fields = .fetch :fields, @model.export_fields @header = @fields.keys end |
Instance Method Details
#data ⇒ Object
91 92 93 94 95 96 97 98 99 |
# File 'lib/easy_export.rb', line 91 def data CSV.generate do |csv| csv << @header scoped_models.each do |model| csv << generate_row(model) end end end |
#file_name ⇒ Object
101 102 103 104 105 |
# File 'lib/easy_export.rb', line 101 def file_name = I18n.l(Time.zone.now, format: :short_date_only).parameterize model_name = @model.name.demodulize.pluralize "#{model_name}-#{timestamp}.csv" end |
#file_type ⇒ Object
107 108 109 |
# File 'lib/easy_export.rb', line 107 def file_type 'text/csv' end |