Skip to content

Instantly share code, notes, and snippets.

@tedgrubb
Created July 16, 2013 17:29
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 tedgrubb/6010779 to your computer and use it in GitHub Desktop.
Save tedgrubb/6010779 to your computer and use it in GitHub Desktop.
ActiveResource PATCH with ActiveModel::Dirty. Redefine 'update' to use PATCH instead of PUT. To have a true PATCH we only want to send the changed attributes. We tap into ActiveModel::Dirty's use of 'attribute_will_change!' method before saving the object. This writes changes to the 'changes' hash in our update method.
class ActiveResource::Base
include ActiveModel::Dirty
def update_attribute(name, value)
self.send :"#{name}_will_change!"
self.send("#{name}=".to_sym, value)
self.save
end
def update_attributes(attributes)
attributes.map{|k,v| self.send :"#{k}_will_change!" }
load(attributes, false) && save
end
# Update the resource on the remote service.
def update
run_callbacks :update do
updates = {}
changes.map{|k, v| updates[k.to_sym] = v[1] }
encoded_updates = updates.send("to_#{self.class.format.extension}")
connection.patch(element_path(prefix_options), encoded_updates, self.class.headers).tap do |response|
load_attributes_from_response(response)
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment