Sha256: 63c3e0f3f7481698ce14b3156a551e1735e643462532d106c46f3736aa022329

Contents?: true

Size: 1.6 KB

Versions: 9

Compression:

Stored size: 1.6 KB

Contents

# To change this template, choose Tools | Templates
# and open the template in the editor.

module ExcelBase
      
  def sanitize_sheet_name( name )
    name.gsub(/[\[\]:\*\/\\\?]/, '')
  end
  
  # Helpers for dealing with Active Record models and collections
  
  def ar_to_headers( records )
    return if( !records.first.is_a?(ActiveRecord::Base) || records.empty?)
      
    headers = records.first.class.columns.collect( &:name )    
    set_headers( headers )
  end
      
    
  # Pass a set of AR records
  def ar_to_xls(records, options = {})
    return if( ! records.first.is_a?(ActiveRecord::Base) || records.empty?)
      
    row_index = 
      if(options[:no_headers])
      0
    else
      ar_to_headers( records )
      1
    end
      
    records.each do |record|
      ar_to_xls_row(row_index, 0, record)
        
      row_index += 1
    end
  end
   

  # Save data from an AR record to the current row, based on the record's columns [c1,c2,c3]
  # Returns the number of the final column written to  
  def ar_to_xls_row(row, start_column, record)
    return unless( record.is_a?(ActiveRecord::Base))
        
    column = start_column
    record.class.columns.each do |connection_column|    
      ar_to_xls_cell(row, column, record, connection_column)
      column += 1
    end
    column
  end
  
  def ar_to_xls_cell(row, column, record, connection_column)  
    begin
      datum = record.send(connection_column.name)

      self[row, column] = datum
    rescue => e
      puts "Failed to export #{datum} from #{connection_column.inspect} to column #{column}"
      puts e, e.backtrace
    end
  end
end

Version data entries

9 entries across 9 versions & 1 rubygems

Version Path
datashift-0.15.0 lib/applications/excel_base.rb
datashift-0.14.0 lib/applications/excel_base.rb
datashift-0.13.0 lib/applications/excel_base.rb
datashift-0.12.1 lib/applications/excel_base.rb
datashift-0.12.0 lib/applications/excel_base.rb
datashift-0.11.1 lib/applications/excel_base.rb
datashift-0.11.0 lib/applications/excel_base.rb
datashift-0.10.2 lib/applications/excel_base.rb
datashift-0.10.1 lib/applications/excel_base.rb