Class: BaseCRM::Sync

Inherits:
Object
  • Object
show all
Defined in:
lib/basecrm/sync.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(options) ⇒ Sync

Intantiate a new BaseCRM Sync API V2 high-level wrapper

Parameters:

  • options (Hash)

    Wrapper options

Options Hash (options):

  • :device_uuid (String)

    Device’s UUID.

  • :client (BaseCRM::Client)

    BaseCRM API v2 client instance.

Raises:

See Also:



19
20
21
22
23
24
# File 'lib/basecrm/sync.rb', line 19

def initialize(options)
  @device_uuid = options[:device_uuid]
  @client = options[:client]

  validate!
end

Instance Attribute Details

#clientObject (readonly)

Returns the value of attribute client.



4
5
6
# File 'lib/basecrm/sync.rb', line 4

def client
  @client
end

#device_uuidObject (readonly)

Returns the value of attribute device_uuid.



3
4
5
# File 'lib/basecrm/sync.rb', line 3

def device_uuid
  @device_uuid
end

Instance Method Details

#fetch(&block) ⇒ Object

Perform a full synchronization flow. See the following example:

client = BaseCRM::Client.new(access_token: "<YOUR_ACCESS_TOKEN>")
sync = BaseCRM::Sync.new(client: client, device_uuid: "<YOUR_DEVICES_UUID>")
sync.fetch do |meta, resource|
  DB.send(meta.sync.event_type, entity) ? meta.sync.ack : meta.sync.nack
end

Parameters:

  • block (Proc)

    Procedure that will be called for every item in the queue. Takes two input arguments: SyncMeta instance associated with the resource, and the resource. You should use either ‘SyncQueue#ack` or `SyncQueue#nack` to return value from the block.

Returns:

  • nil



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
67
# File 'lib/basecrm/sync.rb', line 39

def fetch(&block)
  return unless block_given?

  # Set up a new synchronization session for given device's UUID
  session = @client.sync.start(@device_uuid)

  # Check if there is anything to synchronize
  return unless  session && session.id

  # Drain the main queue unitl there is no more data (empty array)
  loop do
    queued_data = @client.sync.fetch(@device_uuid, session.id)

    # nothing more to synchronize ?
    break unless queued_data

    # something bad at the backend
    next if queued_data.empty?

    ack_keys = []
    queued_data.each do |sync_meta, resource|
      op, ack_key = block.call(sync_meta, resource)
      ack_keys << ack_key if op == :ack
    end

    # As we fetch new data, we need to send ackwledgement keys - if any
    @client.sync.ack(@device_uuid, ack_keys) unless ack_keys.empty?
  end
end