Dragonfly

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

Dragonfly.app

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/]
end

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!

Middleware

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'
end

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

Dragonfly.app(:assets)

you can pass a name argument to use

use Dragonfly::Middleware, :assets

to_app

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”.

to_response

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

Dragonfly.app.fetch('some/uid').thumb('40x30').to_response
    # ===> [200, {'Content-Type' => 'image/png',...}, <body> ]
run app

Sinatra

to_response plays nicely with Sinatra for creating endpoints with nice urls

get '/image/:size' do |size|
  Dragonfly.app.fetch_file('~/some/image.png').thumb(size).to_response(env)
end

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