Created
May 2, 2014 20:26
-
-
Save juanhiplogiq/168856a307ff1327fecb to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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