public

Serving CouchDB attachments with Rails 3

  • Download Gist
couchdb_attachments.rb
Ruby
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24
module CouchDBAttachments
def attachment(*args)
lambda do |env|
request = ActionDispatch::Request.new(env)
doc = DocWithAttachments.get(request.params[:doc])
serve_attachment(doc, request.params[:path])
end
end
 
private
 
# TODO: Add whatever you want
def serve_attachment(doc, filename)
if doc && attachment = doc["_attachments"][filename]
headers = {}
headers["Content-Type"] = attachment["content_type"]
headers["Content-Disposition"] = "inline; filename=#{filename}"
headers["X-Accel-Redirect"] = "/couch/#{doc.database.name}/#{doc["_id"]}/#{filename}"
[200, headers, []]
else
[404, { "Content-Type", "text/html" }, []]
end
end
end
nginx.conf
Nginx
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32
http {
include mime.types;
default_type application/octet-stream;
 
upstream couchdb {
server 127.0.0.1:5984;
}
 
upstream unicorn {
server 127.0.0.1:3000;
}
 
server {
listen 7000;
server_name proxy.caprica.local;
 
location / {
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_set_header Host $http_host;
proxy_redirect off;
proxy_pass http://unicorn/;
}
 
location /couch/ {
internal;
proxy_set_header X-Real-IP $remote_addr;
proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;
proxy_pass http://couchdb/;
}
}
}
routes.rb
Ruby
1 2 3 4 5
Example::Application.routes.draw do |map|
extend CouchDBAttachments
 
match "/assets/:doc/*path", :to => attachment()
end

Please sign in to comment on this gist.

Something went wrong with that request. Please try again.