Skip to content

Instantly share code, notes, and snippets.

@colindensem
Forked from wildchild/couchdb_attachments.rb
Created July 24, 2011 09:53
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save colindensem/1102462 to your computer and use it in GitHub Desktop.
Save colindensem/1102462 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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment