Skip to content

Instantly share code, notes, and snippets.

@wildchild
Created May 20, 2010 07:32
Show Gist options
  • Star 4 You must be signed in to star a gist
  • Fork 6 You must be signed in to fork a gist
  • Save wildchild/407311 to your computer and use it in GitHub Desktop.
Save wildchild/407311 to your computer and use it in GitHub Desktop.
Serving CouchDB attachments with Rails 3
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
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/;
}
}
}
Example::Application.routes.draw do |map|
extend CouchDBAttachments
match "/assets/:doc/*path", :to => attachment()
end
@wildchild
Copy link
Author

Inspired by Matt's article with code example for Merb's awesome router http://merbist.com/2009/07/13/ruby-authentication-of-couchdb-requests.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment