Skip to content

Instantly share code, notes, and snippets.

@juanhiplogiq
Created May 2, 2014 20:26
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save juanhiplogiq/168856a307ff1327fecb to your computer and use it in GitHub Desktop.
Save juanhiplogiq/168856a307ff1327fecb to your computer and use it in GitHub Desktop.
class ExternalResourcePersister
attr_reader :record, :resource
def initialize( resource, record = nil )
@resource = resource
@record = record
end
def create!
raise ActiveResource::ResourceInvalid if !resource.valid?
record_attrs = record_attributes
record_class.create!(record_attrs)
end
def update!
record_attrs = record_attributes
record = record_class.find_by(remote_id: record_attrs[:remote_id]) unless record
record.update!(record_attrs)
record
end
def create_or_update!
if record_class.find_by(remote_id: resource.id)
update!
else
create!
end
end
protected
def record_attributes
record_attrs = resource.attributes.clone
record_attrs[:remote_id] = record_attrs.delete(:id)
record_attrs.reject{|k,v| !record_class.new.attributes.keys.member?(k.to_s) }
end
def record_class
resource.class.name.demodulize.constantize
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment