all specs pass; refined attachment api

This commit is contained in:
Chris Anderson 2009-02-02 15:24:31 -08:00
parent bd2dafd107
commit 60c577963d
2 changed files with 30 additions and 11 deletions

View file

@ -87,27 +87,28 @@ module CouchRest
end
# GET an attachment directly from CouchDB
def fetch_attachment(docid, name)
slug = escape_docid(docid)
name = CGI.escape(name)
RestClient.get "#{@uri}/#{slug}/#{name}"
def fetch_attachment(doc, name)
# slug = escape_docid(docid)
# name = CGI.escape(name)
uri = uri_for_attachment(doc, name)
RestClient.get uri
# "#{@uri}/#{slug}/#{name}"
end
# PUT an attachment directly to CouchDB
def put_attachment(doc, name, file, options = {})
docid = escape_docid(doc['_id'])
name = CGI.escape(name)
uri = if doc['_rev']
"#{@uri}/#{docid}/#{name}?rev=#{doc['_rev']}"
else
"#{@uri}/#{docid}/#{name}"
end
uri = uri_for_attachment(doc, name)
JSON.parse(RestClient.put(uri, file, options))
end
# DELETE an attachment directly from CouchDB
def delete_attachment doc, name
uri = uri_for_attachment(doc, name)
# this needs a rev
JSON.parse(RestClient.delete(uri))
end
@ -280,9 +281,17 @@ module CouchRest
private
def uri_for_attachment doc, name
docid = escape_docid(doc['_id'])
if doc.is_a?(String)
puts "CouchRest::Database#fetch_attachment will eventually require a doc as the first argument, not a doc.id"
docid = doc
rev = nil
else
docid = doc['_id']
rev = doc['_rev']
end
docid = escape_docid(docid)
name = CGI.escape(name)
rev = "?rev=#{doc['_rev']}" if doc['_rev']
rev = "?rev=#{doc['_rev']}" if rev
"#{@root}/#{docid}/#{name}#{rev}"
end

View file

@ -30,6 +30,14 @@ module CouchRest
@@database
end
def id
self['_id']
end
def rev
self['_rev']
end
# copies the document to a new id. If the destination id currently exists, a rev must be provided.
# <tt>dest</tt> can take one of two forms if overwriting: "id_to_overwrite?rev=revision" or the actual doc
# hash with a '_rev' key
@ -67,6 +75,7 @@ module CouchRest
# saves an attachment directly to couchdb
def put_attachment(name, file, options={})
raise ArgumentError, "doc must be saved" unless self.rev
raise ArgumentError, "doc.database required to put_attachment" unless database
result = database.put_attachment(self, name, file, options)
self['_rev'] = result['rev']
@ -75,6 +84,7 @@ module CouchRest
# returns an attachment's data
def fetch_attachment(name)
raise ArgumentError, "doc must be saved" unless self.rev
raise ArgumentError, "doc.database required to put_attachment" unless database
database.fetch_attachment(self, name)
end