Module: Importer::Adapters::DataMapperAdapter::ClassMethods

Defined in:
lib/importer/adapters/data_mapper_adapter.rb

Instance Method Summary collapse

Instance Method Details

#find_on_import(import, attributes) ⇒ Object

Determines whether a detected object already exists in database. By default it tries to find an existing objects by id of the detected one. Returns the object or nil if it’s not found. Override this method in your model to change that default behavior.

  • import - current import

  • attributes - detected object’s attributes hash



86
87
88
# File 'lib/importer/adapters/data_mapper_adapter.rb', line 86

def find_on_import(import, attributes)
  get(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 returns instance of Import class that contains detailed report of import process, you can implement your own Import class and force the importer to use it by passing it’s class here

  • import_options - options passed to Import instance on it’s initialization



47
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
# File 'lib/importer/adapters/data_mapper_adapter.rb', line 47

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

  transaction do
    data.each do |attributes|
      imported_object = import.build_imported_object

      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.uniq
      end

      imported_object.object = object

      import.add_object(imported_object)
    end
  end

  import
end