Skip to content

Instantly share code, notes, and snippets.

@carlqt
Last active August 5, 2021 12:37
Show Gist options
  • Save carlqt/c7790b15658b3cb8e0dc3c7c91d3d158 to your computer and use it in GitHub Desktop.
Save carlqt/c7790b15658b3cb8e0dc3c7c91d3d158 to your computer and use it in GitHub Desktop.
Pseudocode for update_or_create
class SelfCollectStation
def self.update_or_create(params)
station = detect_or_initialize_by(extension_id: attributes[:extension_id])
if station.persisted?
station.update(attributes)
else
station.save
end
end
def self.detect_or_initialize_by(params)
if loaded?
detect { |record| record.extension_id == params[:extension_id] } || new(params)
else
find_or_initialize_by(params)
end
end
end
module SelfCollectStations
module Synchronizers
class Base
attr_reader :data,
:country,
:attribute_mapper_class,
:provider_name
attr_accessor :prepared_data
def initialize(data, country:, attribute_mapper_class:, provider_name:)
@data = data
@country = country
@attribute_mapper_class = attribute_mapper_class
@provider_name = provider_name
end
def call
self.prepared_data = prepare_data_for_sync
self_collect_stations = SelfCollectStation.where(external_id: external_ids, provider: provider_name)
prepared_data.map do |attributes|
self_collect_stations.update_or_create(attributes)
end
end
private
def resources
JSON.parse(data)
end
def prepare_data_for_sync
resources.each_with_object({}) do |api_record, memo|
record = attribute_mapper_class.new(record: api_record, country: country, provider_name: provider_name)
memo[record.external_id] = record
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment