class EasyExport::Exporter
Public Class Methods
new(options = {})
click to toggle source
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
# 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
Public Instance Methods
data()
click to toggle source
# 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()
click to toggle source
# 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_type()
click to toggle source
# File lib/easy_export.rb, line 107 def file_type 'text/csv' end
Protected Instance Methods
generate_row(model)
click to toggle source
Generate an array representing a CSV row by iterating over @fields and using the 2nd item in each array as a value getter. It can be either a proc that is called in the context of the model, a symbol representing a method to call on the model, or a static value.
# File lib/easy_export.rb, line 121 def generate_row(model) @fields.map do |_, value_proc| if value_proc.is_a? Proc begin model.instance_exec &value_proc rescue NameError => e # This happens when the model is a GroupSession hash that was returned by the @scope # when the user selects GroupSession in the calendar filters # TODO: Have the AppointmentFilter convert those # hashes into AR like objects that respond to all # the same methods Appointments do. # For now, just put an error in this field. "Error getting field value" end elsif model.respond_to? value_proc model.send value_proc else value_proc end end end
scoped_models()
click to toggle source
# File lib/easy_export.rb, line 113 def scoped_models @scope.call @options end