Module: Importer::Adapters::MongoMapperAdapter::ClassMethods

Defined in:
lib/importer/adapters/mongo_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



87
88
89
# File 'lib/importer/adapters/mongo_mapper_adapter.rb', line 87

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

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

Performs actual import

Note: unlike with ActiveRecord adapter, import process is not wrapped in a transaction since mongodb does not support them.

  • 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



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

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)

  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

  import
end