Sha256: 5cc97adc6fb8ebe2b02222a7568b23b3c7d39b3b24c87ee775a011cb4e7d1f7c

Contents?: true

Size: 1.67 KB

Versions: 8

Compression:

Stored size: 1.67 KB

Contents

# frozen_string_literal: true

module Consyncful
  ##
  # Takes a mapped item from Contentful and creates/updates/deletes
  # the relevant model in the local database.
  class PersistedItem
    DEFAULT_LOCALE = 'en-NZ'

    def initialize(item, sync_id, stats)
      @item = item
      @sync_id = sync_id
      @stats = stats
    end

    def persist
      puts Rainbow("syncing: #{@item.id}").yellow

      if @item.deletion? || @item.excluded_by_tag?
        delete_model(@item.id, @stats)
      else
        create_or_update_model(@item, @sync_id, @stats)
      end
    end

    private

    def delete_model(id, stats)
      Base.find_by(id: id).destroy
      stats.record_deleted
    rescue Mongoid::Errors::DocumentNotFound
      puts Rainbow("Deleted record not found: #{id}").yellow
      nil
    end

    def create_or_update_model(item, sync_id, stats)
      return if item.type.nil?

      instance = find_or_initialize_item(item)
      update_stats(instance, stats)

      reset_fields(instance)

      item.mapped_fields(DEFAULT_LOCALE).each do |field, value|
        instance[field] = value
      end

      instance[:sync_id] = sync_id

      instance.save
    end

    def find_or_initialize_item(item)
      model_class(item.type).find_or_initialize_by(id: item.id)
    end

    def update_stats(instance, stats)
      if instance.persisted?
        stats.record_updated
      else
        stats.record_added
      end
    end

    def model_class(type)
      Base.model_map[type] || Base
    end

    def reset_fields(instance)
      instance.attributes.each do |field_name, _value|
        next if field_name.in? %w[_id _type]

        instance[field_name] = nil
      end
    end
  end
end

Version data entries

8 entries across 8 versions & 1 rubygems

Version Path
consyncful-1.0.1 lib/consyncful/persisted_item.rb
consyncful-1.0.0 lib/consyncful/persisted_item.rb
consyncful-0.9.0 lib/consyncful/persisted_item.rb
consyncful-0.8.0 lib/consyncful/persisted_item.rb
consyncful-0.7.3 lib/consyncful/persisted_item.rb
consyncful-0.7.2 lib/consyncful/persisted_item.rb
consyncful-0.7.1 lib/consyncful/persisted_item.rb
consyncful-0.7.0 lib/consyncful/persisted_item.rb