Image/asset management for winners

GitHub Repository

Using with Rack

Rack provides a standard interface for interacting with web servers written in Ruby.

A Dragonfly app is a Rack app, that is to say


responds to call in a Rack-compatible way.

Running as standalone

Running rackup with the simple config.ru file

require 'dragonfly'
run Dragonfly.app

will start a server.

Making a GET request to the URL

url = Dragonfly.app.fetch('some/uid').url
url  # ==> "/W1siZiIsInNvbWUvdWlkIl1d"

will return the content stored in the default file datastore with uid (i.e. relative path) “some/uid”, if it exists.

In reality, the app will usually need configuring. See Configuration for more details.

Here’s an example of a config.ru file for a standalone server for resizing images from publicdomainpictures.net

require 'dragonfly'

Dragonfly.app.configure do
  plugin :imagemagick
  fetch_url_whitelist [/publicdomainpictures/]

run Dragonfly.app

When you make a GET request to the URL

url = Dragonfly.app.fetch_url("www.publicdomainpictures.net/pictures/20000/velka/dragonfly-1317422772YLc.jpg").thumb('300x300').url
url   # ==> "/W1siZnUiLCJodHRwOi8vd3d3LnB1YmxpY2RvbWFpbn..."

you get a resized image!


Dragonfly provides a simple middleware which mounts the Dragonfly app so that it will handle requests it knows about and pass on ones it doesn’t.

Dragonfly.app.configure do
  url_format '/media/:job'

use Dragonfly::Middleware

run SomeOtherApp
GET /media/Wsdiglk...

gets handled by Dragonfly while

GET /blah

gets passed on to SomeOtherApp.

To mount a named (i.e. non-default) Dragonfly app


you can pass a name argument to use

use Dragonfly::Middleware, :assets


Dragonfly Job objects can be converted into a Rack-compatible “app” that responds to call

app = Dragonfly.app.fetch('some/uid').thumb('40x30').to_app   # responds to "call"
run app

Visiting this Rack app will always give a 40x30 version of the image stored with uid “some/uid”.


A standard Rack response is an array composed of

[status_code, headers, body]

Dragonfly Job objects can be converted into one of these arrays with to_response

    # ===> [200, {'Content-Type' => 'image/png',...}, <body> ]
run app


to_response plays nicely with Sinatra for creating endpoints with nice urls

get '/image/:size' do |size|

Passing in env allows the response to take into account request headers e.g. for cached responses.