Created
July 16, 2013 17:29
-
-
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.
This file contains hidden or 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 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