-
-
Save darkhelmet/270151 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'snip_snap' | |
require 'hpricot' | |
module Rack | |
# = Rack::Snapshot | |
# | |
# Takes the image tags in your page and expands them using some of the popular | |
# image sharing services. Currently supports these services: | |
# | |
# * Skitch | |
# * Img.ly | |
# * Twitpic | |
# * Yfrog | |
# * Flickr (requires setting the API key - see below) | |
# * Twitgoo | |
# | |
# For example, this image tag that links to the public version of a snapshot: | |
# | |
# <img src="http://img.ly/3ey" class="expand" /> | |
# | |
# Might be expanded to: | |
# | |
# <img class="expand" src="http://img.ly/uploads/000/012/434/large_ChillPill13.jpg" /> | |
# | |
# This middleware will attempt to expand any image tag with the class of "expand" by default, | |
# but this can be overridden: | |
# | |
# use Rack::Snapshot, :class_name => 'snapshot' | |
# | |
# See Rack::Snapsnot#new for recognized options. | |
# | |
class Snapshot | |
# Recognized options: | |
# | |
# +class_name+ | |
# Override the default class ("expand") with a name of your choosing. Image | |
# tags that contain this class name will be subject to expansion through the | |
# appropriate API. | |
# | |
# +flickr_api_key+ | |
# If provided, will allow you to expand full URLs for the Flickr service. | |
# | |
def initialize(app, options = {}) | |
self.options = options | |
@app = app | |
end | |
def call(env) | |
status, @headers, @response = @app.call(env) | |
if html? | |
(document/"img[@class~='#{@image_class_name}']").each do |image| | |
image['src'] = full_image_url(image) | |
end | |
@response = document.to_s | |
@headers['Content-Length'] = @response.length.to_s | |
end | |
[status, @headers, [@response]] | |
end | |
def options=(options) | |
@image_class_name = options[:class_name] || 'expand' | |
SnipSnap.flickr_api_key = options[:flickr_api_key] | |
end | |
private | |
def response_body | |
body = String.new | |
@response.each {|line| body << line } | |
body | |
end | |
def document | |
@document ||= Hpricot(response_body) | |
end | |
def full_image_url(image) | |
source = image['src'] | |
client = SnipSnap.from_url(source) | |
if client.image? | |
source = client.image_url | |
end | |
source | |
end | |
def html? | |
@headers.fetch('Content-Type', '').include?('text/html') | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment