class Consyncful::PersistedItem

Takes a mapped item from Contentful and creates/updates/deletes the relevant model in the local database.

Constants

DEFAULT_LOCALE

Public Class Methods

new(item, sync_id, stats) click to toggle source
# File lib/consyncful/persisted_item.rb, line 10
def initialize(item, sync_id, stats)
  @item = item
  @sync_id = sync_id
  @stats = stats
end

Public Instance Methods

persist() click to toggle source
# File lib/consyncful/persisted_item.rb, line 16
def persist
  puts Rainbow("syncing: #{@item.id}").yellow
  if @item.deletion?
    delete_model(@item.id, @stats)
  else
    create_or_update_model(@item, @sync_id, @stats)
  end
end

Private Instance Methods

create_or_update_model(item, sync_id, stats) click to toggle source
# File lib/consyncful/persisted_item.rb, line 35
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
delete_model(id, stats) click to toggle source
# File lib/consyncful/persisted_item.rb, line 27
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
find_or_initialize_item(item) click to toggle source
# File lib/consyncful/persisted_item.rb, line 52
def find_or_initialize_item(item)
  model_class(item.type).find_or_initialize_by(id: item.id)
end
model_class(type) click to toggle source
# File lib/consyncful/persisted_item.rb, line 64
def model_class(type)
  Base.model_map[type] || Base
end
reset_fields(instance) click to toggle source
# File lib/consyncful/persisted_item.rb, line 68
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
update_stats(instance, stats) click to toggle source
# File lib/consyncful/persisted_item.rb, line 56
def update_stats(instance, stats)
  if instance.persisted?
    stats.record_updated
  else
    stats.record_added
  end
end