Class: ActiveExport::Csv

Inherits:
Base
  • Object
show all
Defined in:
lib/active_export/csv.rb

Instance Attribute Summary

Attributes inherited from Base

#config, #eval_methods, #label_keys, #label_prefix, #namespace, #source, #source_name

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from Base

build_label_keys_and_eval_methods, #build_label_keys_and_eval_methods!, #convert, #default_scope, #initialize, #key_name, translate, #translate

Constructor Details

This class inherits a constructor from ActiveExport::Base

Class Method Details

.export(data, source, namespace, options = {}) ⇒ Object

Parameters:

  • data (Array, ActiveRecord::Relation)
  • source (Symbol, String)
  • namespace (Symobl, String)
  • options (Hash) (defaults to: {})

    ({})

Options Hash (options):

  • :eval_methods (Array)
  • :label_keys (Array)
  • :label_prefix (String)
  • :csv_options (Hash) — default: see http://ruby-doc.org/stdlib-1.9.2/libdoc/csv/rdoc/CSV.html


17
18
19
# File 'lib/active_export/csv.rb', line 17

def self.export(data, source, namespace, options = {})
  new(source, namespace, options).export(data, options)
end

Instance Method Details

#export(data, options = {}) ⇒ Object



21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/active_export/csv.rb', line 21

def export(data, options = {})
  return '' if data.length <= 0 && eval_methods.nil?
  csv_options = self.config.default_csv_options.merge( options[:csv_options] || {} )

  each_method_name = data.respond_to?(:find_each) ? 'find_each' : 'each'
  # 1.9.2
  CSV.generate(csv_options) do |csv|
    csv << generate_header
    data.send(each_method_name) do |f|
      csv << generate_value(f)
    end
  end
end

#generate_headerObject



35
36
37
38
39
# File 'lib/active_export/csv.rb', line 35

def generate_header
  self.label_keys.inject([]) {|result, key|
    result << translate(key_name(key))
  }
end

#generate_value(row) ⇒ Object



41
42
43
44
45
46
# File 'lib/active_export/csv.rb', line 41

def generate_value(row)
  self.eval_methods.inject([]){|result, f|
    v = row.send(:eval, f) rescue nil
    result << convert(v)
  }
end