Module: Importer::ClassMethods

Defined in:
lib/importer.rb

Instance Method Summary collapse

Instance Method Details

#find_on_import(import, attributes) ⇒ Object

Overload find_on_import method to find existing objects while importing an object. This is used to determine wheter an imported should add a new object or just modify an existing one. By default it searches records by id.



89
90
91
# File 'lib/importer.rb', line 89

def find_on_import(import, attributes)
  find_by_id(attributes["id"])
end

#import(file, options = {}) ⇒ Object

The import process is wrapped in a transaction, so if anything goes wrong there is no harm done.

  • file - path to an XML or CVS file, you can also import from other data formats, but you also need to provide a custom parser to read it

Possible options:

  • parser - by default the parser is determined from file extension, but you can force the imported to use another one by passing it’s class here

  • import - by default importer tries to store import summary in database, so it uses ActiveRecord import, to use other import type pass it’s instance here



48
49
50
51
52
53
54
55
56
57
58
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
# File 'lib/importer.rb', line 48

def import(file, options = {})
  import = options[:import] || Importer::Import::ActiveRecord.create
  parser = options[:parser] || Importer::Parser.get_klass(file)
  data   = parser.run(file)

  transaction do
    import.start!

    imported_object_klass = Importer::ImportedObject.get_klass(import)

    data.each do |attributes|
      imported_object = imported_object_klass.new(:import => import)

      if object = find_on_import(import, attributes)
        imported_object.state = "existing_object"
      else
        object                = new
        imported_object.state = "new_object"
      end

      imported_object.data = attributes
      object.merge_attributes_on_import(import, attributes)

      unless object.save
        imported_object.state             = "invalid_object"
        imported_object.validation_errors = object.errors.full_messages
      end

      imported_object.object = object
      imported_object.save
    end

    import.finish!
  end

  import
end