Class: SyncableModels::Importer::Import

Inherits:
Object
  • Object
show all
Defined in:
lib/syncable_models/importer.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initializeImport

Returns a new instance of Import.



9
10
11
# File 'lib/syncable_models/importer.rb', line 9

def initialize
  @models = {}
end

Instance Attribute Details

#api_keyObject

Returns the value of attribute api_key.



6
7
8
# File 'lib/syncable_models/importer.rb', line 6

def api_key
  @api_key
end

#api_urlObject

Returns the value of attribute api_url.



6
7
8
# File 'lib/syncable_models/importer.rb', line 6

def api_url
  @api_url
end

#destinationObject

Returns the value of attribute destination.



6
7
8
# File 'lib/syncable_models/importer.rb', line 6

def destination
  @destination
end

#modelsObject (readonly)

Returns the value of attribute models.



7
8
9
# File 'lib/syncable_models/importer.rb', line 7

def models
  @models
end

Instance Method Details

#importObject



34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
# File 'lib/syncable_models/importer.rb', line 34

def import
  @models.each do |model_name, params|
    fetch_url = self.api_url + params[:fetch_path]
    sync_url = self.api_url + params[:sync_path]

    conn = Faraday.new(url: fetch_url)
    response = conn.get '', params_with_api_key(destination: destination)

    if response.success?
      response = JSON.parse(response.body)

      if response["status"].to_i == 401
        puts "[SyncableModels::Importer] Wrong api key!"
      end

      if response['objects'] && response['objects'].count > 0
        klass = model_name.constantize
        synced_ids = []

        response['objects'].each do |o|
          result = klass.from_import_hash(o)
          puts "[SyncableModels::Importer] Importing #{model_name} (id=#{o[params[:id_key].to_s]}): #{ result ? 'OK' : 'FAIL' }"
          synced_ids << o[params[:id_key].to_s] if result
        end

        if synced_ids.any?
          conn = Faraday.new(url: sync_url)
          response = conn.get '', params_with_api_key(destination: self.destination, ids: synced_ids)
        end
      end
    end
  end
end

#import_model(class_name, args = {}) ⇒ Object



13
14
15
16
17
18
19
20
21
22
23
# File 'lib/syncable_models/importer.rb', line 13

def import_model(class_name, args = {})
  class_name = class_name.to_s if class_name.is_a?(Class)
  fetch_path = args[:fetch_path] || class_name.underscore.pluralize
  sync_path = args[:sync_path] || "sync_" + class_name.underscore.pluralize
  id_key = args[:id_key] || :uuid
  @models[class_name] = {
    fetch_path: fetch_path,
    sync_path: sync_path,
    id_key: id_key
  }
end

#params_with_api_key(params) ⇒ Object



29
30
31
32
# File 'lib/syncable_models/importer.rb', line 29

def params_with_api_key(params)
  params.merge!(key: api_key) if api_key
  params
end