Class: EasyExport::Exporter

Inherits:
Object
  • Object
show all
Defined in:
lib/easy_export.rb

Instance Method Summary collapse

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 options 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(options = {})
  @options = options
  @model   = options[:model].constantize
  # the @model.export_scope is configured via the `exportable` block
  @scope   = options.fetch :scope, @model.export_scope
  # the fields configured via the `exportable` block
  @fields  = options.fetch :fields, @model.export_fields
  @header  = @fields.keys
end

Instance Method Details

#dataObject



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_nameObject



101
102
103
104
105
# File 'lib/easy_export.rb', line 101

def file_name
  timestamp = I18n.l(Time.zone.now, format: :short_date_only).parameterize
  model_name = @model.name.demodulize.pluralize
  "#{model_name}-#{timestamp}.csv"
end

#file_typeObject



107
108
109
# File 'lib/easy_export.rb', line 107

def file_type
  'text/csv'
end