Module: CommaHeaven::ActiveRecord::ClassMethods::Rails2

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



49
50
51
52
53
54
55
56
57
# File 'lib/comma-heaven/active_record/to_comma_heaven.rb', line 49

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

Instance Method Details

#to_comma_heaven(options = {}) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
# File 'lib/comma-heaven/active_record/to_comma_heaven.rb', line 59

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 = find(:all, :select => "#{table_name}.#{primary_key}", :limit => options[:limit]).map(&:id)
    
    with_exclusive_scope do
      find(:all, :conditions => ["#{columns.table_alias}.#{primary_key} IN (?)", ids], :limit => options[:limit], :joins => columns.joins, :select => columns.select).each do |resource|
        fields = columns.sql_as.inject([]) do |acc, field|
          value = resource.send(field)
          
          if options[:format]
            begin 
              value = value.strftime(options[:format][:datetime]) if (value.is_a?(Date) || value.is_a?(Time)) && options[:format][:datetime]
            rescue 
            end
          end
          
          acc << options[:converter].call(value)
        end
        
        table << FasterCSV::Row.new(headers, fields)
      end
    end
  end
end