module ModelToGooglesheet::Export::ClassMethods

Constants

BATCH_SIZE

Public Instance Methods

export_to_googlesheet(permethod_options={}) click to toggle source
# File lib/model_to_googlesheet/export.rb, line 78
def export_to_googlesheet permethod_options={}
        options = Configuration.merge_configs permethod_options, model_to_googlesheet_configuration
        
        session = GoogleDrive::Session.new_for_gs({
                client_id: options[:client_id], 
                client_secret: options[:client_secret], 
                refresh_token: options[:refresh_token]
        })
        ss = session.get_or_create_ss options[:spreadsheet]
        ws = ss.create_or_recreate_ws options[:worksheet]

        amount_of_batches_to_skip = self.count/BATCH_SIZE
        (0..amount_of_batches_to_skip).each do |skip_n_batches|
                records = limit(BATCH_SIZE).offset(skip_n_batches*BATCH_SIZE)

                -> {
                        records.each do |record|
                                record_hash = record.get_exportable_hash options[:convert_with]
                                ws.export_hash record_hash, update: false, find_by: false
                        end
                        ws.save
                }.rescue(2){
                        # get a new session token (expires in about 1hr)
                        # if this isn't why we failed, refreshing token
                        # is still useful.
                        session = GoogleDrive::Session.new_for_gs({
                                client_id: options[:client_id], 
                                client_secret: options[:client_secret], 
                                refresh_token: options[:refresh_token]
                        })
                        ss = session.exact_ss options[:spreadsheet]
                        ws = ss.worksheet_by_title options[:worksheet]
                }


        end


end