Sha256: daaf166c4160560d14c2f470a9ec480a534c0b0463ad8a78dbe6bb0d1ca4c17d

Contents?: true

Size: 1.63 KB

Versions: 6

Compression:

Stored size: 1.63 KB

Contents

module CsvImportMagic
  class Importer
    attr_reader :source_klass, :importer, :csv_parser_class, :resources

    def initialize(importer_id, resources = nil)
      @importer = ::Importer.find(importer_id)
      @source_klass = importer.source_klass
      @csv_parser_class = importer.parser_klass
      @resources = resources.try(:symbolize_keys!)
      @model = model_with_relation || @source_klass
    end

    def call
      csv_parsed.run!
      csv_parsed.report
      csv_parsed
    end

    def column_separator
      header = content.lines("\r")[0].gsub(/[^,;\t]/, '_')
      header.scan(/[,;\t]/).first
    end

    private

    def model_with_relation
      return if resources.blank?
      resources[:model].classify.constantize.find(resources[:id]).send(resources[:relation])
    end

    def csv_parsed
      model = @model
      importer = @importer

      @csv_parsed ||= csv_parser_class.new(content: content_with_new_header) do
        model model

        after_build do |model|
          if importer.additional_data
            additional_data = JSON.parse(importer.additional_data)
            model.assign_attributes(additional_data) rescue nil
          end
        end
      end
    end

    def content
      @content ||= begin
        content = Paperclip.io_adapters.for(@importer.attachment).read.force_encoding('UTF-8')
        content.encode('UTF-8', content.encoding, invalid: :replace, undef: :replace, universal_newline: true)
      end
    end

    def content_with_new_header
      new_header = importer.columns.join(column_separator.to_s)

      body = content.lines[1..-1].join
      body.prepend(new_header + "\n")
    end
  end
end

Version data entries

6 entries across 6 versions & 1 rubygems

Version Path
csv_import_magic-0.0.7 app/services/csv_import_magic/importer.rb
csv_import_magic-0.0.6 app/services/csv_import_magic/importer.rb
csv_import_magic-0.0.5 app/services/csv_import_magic/importer.rb
csv_import_magic-0.0.4 app/services/csv_import_magic/importer.rb
csv_import_magic-0.0.3 app/services/csv_import_magic/importer.rb
csv_import_magic-0.0.2 app/services/csv_import_magic/importer.rb