Created
December 15, 2009 19:21
-
-
Save pierrel/257205 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
require 'rest_client' | |
require 'json' | |
class Couch | |
def initialize(url) | |
@db = url.gsub(/\/$/, '') | |
end | |
# Updates the given doc by yielding the current state of the doc | |
# and trying to update update_limit times. Returns the new doc | |
# if the doc was successfully updated without hitting the limit | |
def update_doc(doc_id, update_limit=20) | |
url = @db + '/' + doc_id | |
resp = {'ok' => false} | |
new_doc = nil | |
until resp['ok'] or update_limit == 0 | |
doc = JSON.parse(RestClient.get(url)) # grab the doc | |
new_doc = yield doc # give it to the caller to be updated | |
begin | |
resp = JSON.parse(RestClient.put(url, JSON.generate(new_doc))) # try to PUT the updated doc into the db | |
rescue RestClient::RequestFailed => e | |
if e.http_code == 409 # Update collision | |
update_limit -= 1 | |
else # some other error | |
raise e | |
end | |
end | |
end | |
raise RestClient::RequestFailed.new unless resp['ok'] | |
new_doc | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment