Permalink
Browse files

Add Rack::CSSHTTPRequest middleware

  • Loading branch information...
cee-dub committed Jan 23, 2009
1 parent 31370b7 commit fe510efdf75e43aab43472497dc519f62d21fa4a
Showing with 50 additions and 0 deletions.
  1. +2 −0 README.rdoc
  2. +1 −0 lib/rack/contrib.rb
  3. +25 −0 lib/rack/contrib/csshttprequest.rb
  4. +22 −0 test/spec_rack_csshttprequest.rb
View
@@ -29,6 +29,8 @@ interface:
* Rack::Callbacks - Implements DLS for pure before/after filter like Middlewares.
* Rack::Config - Shared configuration for cooperative middleware.
* Rack::NotFound - A default 404 application.
+* Rack::CSSHTTPRequest - Adds CSSHTTPRequest support by encoding responses as
+ CSS for cross-site AJAX-style data loading
=== Use
View
@@ -8,6 +8,7 @@ def self.release
end
autoload :BounceFavicon, "rack/contrib/bounce_favicon"
+ autoload :CSSHTTPRequest, "rack/contrib/csshttprequest"
autoload :ETag, "rack/contrib/etag"
autoload :GarbageCollector, "rack/contrib/garbagecollector"
autoload :JSONP, "rack/contrib/jsonp"
@@ -0,0 +1,25 @@
+require 'csshttprequest'
+
+module Rack
+
+ # A Rack middleware for providing CSSHTTPRequest responses.
+ class CSSHTTPRequest
+
+ def initialize(app)
+ @app = app
+ end
+
+ # Proxies the request to the application then encodes the response with
+ # the CSSHTTPRequest encoder
+ def call(env)
+ status, headers, body = @app.call(env)
+ assembled_body = ""
+ body.each { |s| assembled_body << s } # call down the stack
+ encoded_response = ::CSSHTTPRequest.encode(assembled_body)
+ headers['Content-Length'] = encoded_response.length.to_s
+ headers['Content-Type'] = 'text/css'
+ [status, headers, encoded_response]
+ end
+
+ end
+end
@@ -0,0 +1,22 @@
+require 'rack/mock'
+require 'rack/contrib/csshttprequest'
+
+context "Rack::CSSHTTPRequest" do
+
+ specify "should modify the content length to the correct value" do
+ test_body = '{"bar":"foo"}'
+ encoded_body = CSSHTTPRequest.encode(test_body)
+ app = lambda { |env| [200, {'Content-Type' => 'text/plain'}, test_body] }
+ request = Rack::MockRequest.env_for("/")
+ headers = Rack::CSSHTTPRequest.new(app).call(request)[1]
+ headers['Content-Length'].should == (encoded_body.length).to_s
+ end
+
+ specify "should modify the content type to the correct value" do
+ test_body = '{"bar":"foo"}'
+ app = lambda { |env| [200, {'Content-Type' => 'text/plain'}, test_body] }
+ request = Rack::MockRequest.env_for("/")
+ headers = Rack::CSSHTTPRequest.new(app).call(request)[1]
+ headers['Content-Type'].should == 'text/css'
+ end
+end

0 comments on commit fe510ef

Please sign in to comment.