Skip to content

Instantly share code, notes, and snippets.

@ender672
Created January 28, 2012 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save ender672/1693521 to your computer and use it in GitHub Desktop.
Save ender672/1693521 to your computer and use it in GitHub Desktop.
Dynamic, image-resizing rack application
require 'rack'
require 'rack/cache'
require './squint'
use Rack::Chunked
use Rack::Cache,
:verbose => true,
:allow_reload => false,
:metastore => 'file:cache/meta',
:entitystore => 'file:cache/ent',
:private_headers => ['Authorization'],
:default_ttl => 5000
run Rack::Squint.new('.', 1000, 1000)
require 'stringio'
require 'rubygems'
require 'rack/utils'
require 'axon'
module Rack
class Squint < File
class ImageBody
def initialize(path, width, height)
@path = path
@width = width
@height = height
end
def each
strio = StringIO.new
Axon.jpeg_file(@path) do |im|
im.fit(@width || im.width, @height || im.height)
im.jpeg(strio)
yield strio.string
end
end
end
def initialize(root, max_width, max_height)
@max_width = max_width
@max_height = max_height
super(root)
end
def serving(env)
header = { "Last-Modified" => F.mtime(@path).httpdate }
header["Content-Type"] = 'image/jpeg'
if env["REQUEST_METHOD"] == "HEAD"
[200, header, []]
else
qs = Utils.parse_query(env["QUERY_STRING"])
width = sane_dimension(qs['width'].to_i, @max_width)
height = sane_dimension(qs['height'].to_i, @max_height)
[200, header, ImageBody.new(@path, width, height)]
end
end
private
def sane_dimension(dim, max)
if max && dim > max then max
elsif dim < 1 then nil
else dim
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment