Sha256: 00b0da39cd8741d96bf9bafb1addd13c8683fb775e6205b03af1a5212fed55c6

Contents?: true

Size: 1.19 KB

Versions: 2

Compression:

Stored size: 1.19 KB

Contents

require 'tmpdir'

module DataForge
  module File
    module CSV
      class CSVRecordFileWriter

        attr_reader :definition, :name, :fields



        def initialize(definition)
          @definition = definition
          @name = definition.name
          @fields = definition.field_names
        end



        def open
          @tempfile_name = tempfile_name
          @csv_file = ::CSV.open @tempfile_name, "w", csv_options
        end



        def close
          @csv_file.close
          FileUtils.move @tempfile_name, definition.file_name
        end



        def write(record)
          @csv_file << fields.map { |field| record[field] }
        end



        private

        def tempfile_name
          Dir::Tmpname.make_tmpname [definition.name.to_s, ".csv"], 1
        end



        def csv_options
          options = {col_sep: definition.delimiter,
                     quote_char: definition.quote,
                     encoding: definition.encoding,
                     write_headers: false}

          options.merge!({write_headers: true,
                          headers: definition.field_names}) if definition.has_header_row
          options
        end

      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
data_forge-0.1.1 lib/data_forge/file/csv/csv_record_file_writer.rb
data_forge-0.1 lib/data_forge/file/csv/csv_record_file_writer.rb