Module: CommaHeaven::ActiveRecord::ClassMethods::Rails3

Defined in:
lib/comma-heaven/active_record/to_comma_heaven.rb

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.extended(base) ⇒ Object



5
6
7
8
9
10
11
12
13
# File 'lib/comma-heaven/active_record/to_comma_heaven.rb', line 5

def self.extended(base)
  base.class_eval do
    base.class_attribute :comma_heaven_columns
    base.comma_heaven_columns = []
    
    base.class_attribute :comma_heaven_associations
    base.comma_heaven_associations = []
  end
end

Instance Method Details

#to_comma_heaven(options = {}) ⇒ Object



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])
    headers = 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(headers, fields)
      end
    end
  end
end