lib/shutterbug/rackapp.rb in shutterbug-0.0.11 vs lib/shutterbug/rackapp.rb in shutterbug-0.1.0
- old
+ new
@@ -1,51 +1,53 @@
# encoding: utf-8
-
module Shutterbug
class Rackapp
- def initialize(app, &block)
+ DefaultHandlers = [
+ Shutterbug::Handlers::ConvertHandler ,
+ Shutterbug::Handlers::JsFileHandler,
+ Shutterbug::Handlers::FileHandlers::PngFile,
+ Shutterbug::Handlers::FileHandlers::HtmlFile
+ ]
+
+ attr_accessor :handlers
+ def add_handler(klass)
+ instance = klass.new(@config)
+ log "adding handler for #{instance.regex} ➙ #{klass.name}"
+ self.handlers[instance.regex] = instance
+ end
+
+ def add_default_handlers
+ DefaultHandlers.each { |h| add_handler(h) }
+ end
+
+ def initialize(app=nil, &block)
+ @handlers = {}
@config = Configuration.instance
yield @config if block_given?
@app = app
- @shutterbug = Service.new(@config)
+ add_default_handlers
log "initialized"
end
- def do_convert(req)
- html = req.POST()['content'] || ""
- width = req.POST()['width'] || 1000
- height = req.POST()['height'] || 700
- css = req.POST()['css'] || ""
-
- signature = @shutterbug.convert(@config.base_url(req), html, css, width, height)
- response_text = "<img src='#{@config.png_path(signature)}' alt='#{signature}'>"
- return good_response(response_text,'text/plain')
- end
-
def call env
- req = Rack::Request.new(env)
- case req.path
- when @config.convert_regex
- do_convert(req)
- when @config.png_regex
- good_response(@shutterbug.get_png_file($1),'image/png')
- when @config.html_regex
- good_response(@shutterbug.get_html_file($1),'text/html')
- when @config.js_regex
- good_response(@shutterbug.get_shutterbug_file, 'application/javascript')
- else
- skip(env)
+ req = Rack::Request.new(env)
+ result = false
+ handlers.keys.each do |path_regex|
+ if req.path =~ path_regex
+ result = handlers[path_regex].handle(self, req, env)
+ end
end
+ result || skip(env)
end
- private
- def good_response(content, type, cache='no-cache')
+ def good_response(content, type, cachable=true)
headers = {}
- headers['Content-Length'] = content.size.to_s
+ size = content.respond_to?(:bytesize) ? content.bytesize : content.size
+ headers['Content-Length'] = size.to_s
headers['Content-Type'] = type
- headers['Cache-Control'] = 'no-cache'
+ headers['Cache-Control'] = 'no-cache' unless cachable
# content must be enumerable.
content = [content] if content.kind_of? String
return [200, headers, content]
end
@@ -53,10 +55,10 @@
puts "★ shutterbug #{Shutterbug::VERSION} ➙ #{string}"
end
def skip(env)
# call the applicaiton default
- @app.call env
+ @app.call env if @app
end
end
end