Class: Importu::Backends::ActiveRecord

Inherits:
Object
  • Object
show all
Defined in:
lib/importu/backends/active_record.rb

Overview

Backend for persisting records to ActiveRecord models.

This backend is automatically registered and detected when your model inherits from ActiveRecord::Base.

Examples:

Basic usage in an importer

class BookImporter < Importu::Importer
  model "Book"
  allow_actions :create, :update
  find_by :isbn
end

Defined Under Namespace

Classes: AssignmentContext

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(model:, finder_fields:, before_save: nil) ⇒ ActiveRecord

This method is part of a private API. You should avoid using this method if possible, as it may be removed or be changed in the future.

Creates a new ActiveRecord backend.



33
34
35
36
37
# File 'lib/importu/backends/active_record.rb', line 33

def initialize(model:, finder_fields:, before_save: nil, **)
  @model = model.is_a?(String) ? self.class.const_get(model) : model
  @finder_fields = finder_fields
  @before_save = before_save
end

Class Method Details

.supported_by_model?(model) ⇒ Boolean

Checks if this backend supports the given model.



23
24
25
# File 'lib/importu/backends/active_record.rb', line 23

def self.supported_by_model?(model)
  model < ActiveRecord::Base # Inherits from
end

Instance Method Details

#create(record) ⇒ Array<(Symbol, ActiveRecord::Base)>

Creates a new record in the database.

Raises:



68
69
70
71
72
# File 'lib/importu/backends/active_record.rb', line 68

def create(record)
  object = @model.new
  perform_assignment(record, object, :create)
  save(record, object)
end

#find(record) ⇒ ActiveRecord::Base?

Finds an existing record matching the import data.



43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/importu/backends/active_record.rb', line 43

def find(record)
  @finder_fields.each do |field_group|
    if field_group.respond_to?(:call) # proc
      object = @model.instance_exec(record, &field_group)
    else
      conditions = field_group.to_h {|f| [f, record[f]]}
      object = @model.where(conditions).first
    end

    return object if object
  end

  nil
end

#unique_id(object) ⇒ Object

The unique id representing the object in the database, if one exists.



59
60
61
# File 'lib/importu/backends/active_record.rb', line 59

def unique_id(object)
  object.respond_to?(:id) ? object.id : nil
end

#update(record, object) ⇒ Array<(Symbol, ActiveRecord::Base)>

Updates an existing record in the database.

Raises:



80
81
82
83
# File 'lib/importu/backends/active_record.rb', line 80

def update(record, object)
  perform_assignment(record, object, :update)
  save(record, object)
end