Sha256: ae7c3776e31b614e615ea03f77f020d704ce920e5b033270ad6892abad373b25

Contents?: true

Size: 2 KB

Versions: 3

Compression:

Stored size: 2 KB

Contents

module CanvasSync::ApiSyncable
  extend ActiveSupport::Concern

  class_methods do
    attr_accessor :api_sync_map, :api_sync_fetch, :api_sync_block

    def api_syncable(map, fetch, &blk)
      self.api_sync_map = map
      self.api_sync_fetch = fetch
      self.api_sync_block = blk
    end
  end

  def sync_from_api(retries: 3)
    update_from_api_params!(request_from_api(retries: retries))
  end

  def request_from_api(retries: 3)
    api_call_with_retry(retries || 3) {
      blk = self.class.api_sync_fetch
      case blk.arity
      when 1
        self.instance_exec(canvas_sync_client, &blk)
      else
        self.instance_exec(&blk)
      end
    }
  end

  def update_from_api_params(api_params)
    api_params = api_params.with_indifferent_access
    apply_block = self.class.api_sync_block
    map = self.class.api_sync_map

    mapped_params = {}
    if map.present?
      map.each do |local_name, remote_name|
        if remote_name.respond_to?(:call)
          mapped_params[local_name] = self.instance_exec(api_params, &remote_name)
        elsif api_params.include?(remote_name)
          mapped_params[local_name] = api_params[remote_name]
          if remote_name == :id
            current_value = send("#{local_name}")
            raise "Mismatched Canvas ID" if current_value.present? && current_value != api_params[remote_name]
          end
        end
      end
    end

    if apply_block.present?
      case apply_block.arity
      when 1
        self.instance_exec(api_params, &apply_block)
      when 2
        self.instance_exec(api_params, mapped_params, &apply_block)
      end
    else
      mapped_params.each do |local_name, val|
        send("#{local_name}=", val)
      end
    end
    self
  end

  def update_from_api_params!(api_params)
    update_from_api_params(api_params)
    save! if changed?
    self
  end

  private

  def api_call_with_retry(retries=3)
    tries ||= retries
    yield
  rescue Faraday::ConnectionFailed => e
    raise e if (tries -= 1).zero?
    sleep 5
    retry
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
canvas_sync-0.9.1 lib/canvas_sync/api_syncable.rb
canvas_sync-0.9.0 lib/canvas_sync/api_syncable.rb
canvas_sync-0.8.4 lib/canvas_sync/api_syncable.rb