Skip to content

Instantly share code, notes, and snippets.

@pierrel
Created December 15, 2009 19:21
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 pierrel/257205 to your computer and use it in GitHub Desktop.
Save pierrel/257205 to your computer and use it in GitHub Desktop.
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