15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
|
# File 'lib/comma-heaven/active_record/to_comma_heaven.rb', line 15
def to_comma_heaven(options = {})
options.symbolize_keys! if options.respond_to?(:symbolize_keys!)
options[:limit] = options[:limit].to_i if options[:limit].kind_of?(String)
options[:converter] ||= lambda { |v| v }
FasterCSV::Table.new([]).tap do |table|
columns = CommaHeaven::Sqler::Columns.new(self, options[:export])
= columns.sql_as
ids = select("#{table_name}.#{primary_key}").limit(options[:limit]).all.map(&:id)
unscoped do
where(["#{columns.table_alias}.#{primary_key} IN (?)", ids]).limit(options[:limit]).joins(columns.joins).select(columns.select).all.each do |resource|
fields = columns.sql_as.inject([]) do |acc, field|
value = resource.send(field)
if options[:format]
begin
value = value.to_time.strftime(options[:format][:datetime]) if value =~ %r{^(\d{4,4})-(\d{2,2})-(\d{2,2})} && options[:format][:datetime]
rescue
end
end
acc << options[:converter].call(value)
end
table << FasterCSV::Row.new(, fields)
end
end
end
end
|