Module: CsvRails::ActiveModel::ClassMethods

Defined in:
lib/csv_rails/active_model.rb

Instance Method Summary collapse

Instance Method Details

#csv_fieldsObject



26
27
28
29
30
31
32
# File 'lib/csv_rails/active_model.rb', line 26

def csv_fields
  if self.is_a?(::ActiveRecord::Relation)
    @klass.attribute_names
  else
    attribute_names
  end
end

#csv_header(fields, scope = nil) ⇒ Object



16
17
18
19
20
21
22
23
24
# File 'lib/csv_rails/active_model.rb', line 16

def csv_header(fields, scope=nil)
  fields.map{|f|
    if scope
      I18n.t("#{scope}.#{f}", :default => human_attribute_name(f))
    else
      human_attribute_name(f)
    end
  }
end

#to_csv(opts = {}) ⇒ Object



5
6
7
8
9
10
11
12
13
14
# File 'lib/csv_rails/active_model.rb', line 5

def to_csv(opts={})
  fields = opts[:fields] || csv_fields
  header = csv_header(fields, opts.delete(:i18n_scope))
  all = if self.respond_to?(:to_a)
          to_a
        else
          send(:all).to_a
        end
  all.to_csv(opts.update(:fields => fields, :header => header))
end