tricycle-rack-contrib 0.9.0

Sign up to get free protection for your applications and to get access to all the features.
Files changed (56) hide show
  1. data/COPYING +18 -0
  2. data/README.rdoc +78 -0
  3. data/Rakefile +97 -0
  4. data/lib/rack/contrib.rb +37 -0
  5. data/lib/rack/contrib/accept_format.rb +46 -0
  6. data/lib/rack/contrib/backstage.rb +20 -0
  7. data/lib/rack/contrib/bounce_favicon.rb +16 -0
  8. data/lib/rack/contrib/callbacks.rb +37 -0
  9. data/lib/rack/contrib/config.rb +16 -0
  10. data/lib/rack/contrib/cookies.rb +50 -0
  11. data/lib/rack/contrib/csshttprequest.rb +39 -0
  12. data/lib/rack/contrib/deflect.rb +137 -0
  13. data/lib/rack/contrib/etag.rb +20 -0
  14. data/lib/rack/contrib/evil.rb +12 -0
  15. data/lib/rack/contrib/garbagecollector.rb +14 -0
  16. data/lib/rack/contrib/jsonp.rb +41 -0
  17. data/lib/rack/contrib/lighttpd_script_name_fix.rb +16 -0
  18. data/lib/rack/contrib/locale.rb +31 -0
  19. data/lib/rack/contrib/mailexceptions.rb +120 -0
  20. data/lib/rack/contrib/nested_params.rb +143 -0
  21. data/lib/rack/contrib/not_found.rb +18 -0
  22. data/lib/rack/contrib/post_body_content_type_parser.rb +40 -0
  23. data/lib/rack/contrib/proctitle.rb +30 -0
  24. data/lib/rack/contrib/profiler.rb +108 -0
  25. data/lib/rack/contrib/relative_redirect.rb +44 -0
  26. data/lib/rack/contrib/response_cache.rb +116 -0
  27. data/lib/rack/contrib/route_exceptions.rb +49 -0
  28. data/lib/rack/contrib/sendfile.rb +142 -0
  29. data/lib/rack/contrib/signals.rb +63 -0
  30. data/lib/rack/contrib/time_zone.rb +25 -0
  31. data/test/404.html +1 -0
  32. data/test/Maintenance.html +1 -0
  33. data/test/mail_settings.rb +12 -0
  34. data/test/spec_rack_accept_format.rb +72 -0
  35. data/test/spec_rack_backstage.rb +26 -0
  36. data/test/spec_rack_callbacks.rb +65 -0
  37. data/test/spec_rack_config.rb +22 -0
  38. data/test/spec_rack_contrib.rb +8 -0
  39. data/test/spec_rack_csshttprequest.rb +66 -0
  40. data/test/spec_rack_deflect.rb +107 -0
  41. data/test/spec_rack_etag.rb +23 -0
  42. data/test/spec_rack_evil.rb +19 -0
  43. data/test/spec_rack_garbagecollector.rb +13 -0
  44. data/test/spec_rack_jsonp.rb +34 -0
  45. data/test/spec_rack_lighttpd_script_name_fix.rb +16 -0
  46. data/test/spec_rack_mailexceptions.rb +97 -0
  47. data/test/spec_rack_nested_params.rb +46 -0
  48. data/test/spec_rack_not_found.rb +17 -0
  49. data/test/spec_rack_post_body_content_type_parser.rb +32 -0
  50. data/test/spec_rack_proctitle.rb +26 -0
  51. data/test/spec_rack_profiler.rb +37 -0
  52. data/test/spec_rack_relative_redirect.rb +78 -0
  53. data/test/spec_rack_response_cache.rb +181 -0
  54. data/test/spec_rack_sendfile.rb +86 -0
  55. data/tricycle-rack-contrib.gemspec +88 -0
  56. metadata +175 -0
data/COPYING ADDED
@@ -0,0 +1,18 @@
1
+ Copyright (c) 2008 The Committers
2
+
3
+ Permission is hereby granted, free of charge, to any person obtaining a copy
4
+ of this software and associated documentation files (the "Software"), to
5
+ deal in the Software without restriction, including without limitation the
6
+ rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
7
+ sell copies of the Software, and to permit persons to whom the Software is
8
+ furnished to do so, subject to the following conditions:
9
+
10
+ The above copyright notice and this permission notice shall be included in
11
+ all copies or substantial portions of the Software.
12
+
13
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
14
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
15
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL
16
+ THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER
17
+ IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN
18
+ CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
data/README.rdoc ADDED
@@ -0,0 +1,78 @@
1
+ = Contributed Rack Middleware and Utilities
2
+
3
+ This package includes a variety of add-on components for Rack, a Ruby web server
4
+ interface:
5
+
6
+ * Rack::ETag - Automatically sets the ETag header on all String bodies.
7
+ * Rack::JSONP - Adds JSON-P support by stripping out the callback param
8
+ and padding the response with the appropriate callback format.
9
+ * Rack::LighttpdScriptNameFix - Fixes how lighttpd sets the SCRIPT_NAME
10
+ and PATH_INFO variables in certain configurations.
11
+ * Rack::Locale - Detects the client locale using the Accept-Language request
12
+ header and sets a rack.locale variable in the environment.
13
+ * Rack::MailExceptions - Rescues exceptions raised from the app and
14
+ sends a useful email with the exception, stacktrace, and contents of the
15
+ environment.
16
+ * Rack::NestedParams - parses form params with subscripts (e.g., * "post[title]=Hello")
17
+ into a nested/recursive Hash structure (based on Rails' implementation).
18
+ * Rack::PostBodyContentTypeParser - Adds support for JSON request bodies. The
19
+ Rack parameter hash is populated by deserializing the JSON data provided in
20
+ the request body when the Content-Type is application/json.
21
+ * Rack::ProcTitle - Displays request information in process title ($0) for
22
+ monitoring/inspection with ps(1).
23
+ * Rack::Profiler - Uses ruby-prof to measure request time.
24
+ * Rack::Sendfile - Enables X-Sendfile support for bodies that can be served
25
+ from file.
26
+ * Rack::Signals - Installs signal handlers that are safely processed after
27
+ a request
28
+ * Rack::StaticCache - Modifies the response headers to facilitiate client and proxy caching for
29
+ static files that minimizes http requests and improves overall load times for second time visitors.
30
+ * Rack::TimeZone - Detects the clients timezone using JavaScript and sets
31
+ a variable in Rack's environment with the offset from UTC.
32
+ * Rack::Evil - Lets the rack application return a response to the client from any place.
33
+ * Rack::Callbacks - Implements DLS for pure before/after filter like Middlewares.
34
+ * Rack::Config - Shared configuration for cooperative middleware.
35
+ * Rack::NotFound - A default 404 application.
36
+ * Rack::CSSHTTPRequest - Adds CSSHTTPRequest support by encoding responses as
37
+ CSS for cross-site AJAX-style data loading
38
+ * Rack::Deflect - Helps protect against DoS attacks.
39
+ * Rack::ResponseCache - Caches responses to requests without query strings
40
+ to Disk or a user provider Ruby object. Similar to Rails' page caching.
41
+ * Rack::RelativeRedirect - Transforms relative paths in redirects to
42
+ absolute URLs.
43
+ * Rack::Backstage - Returns content of specified file if it exists, which makes
44
+ it convenient for putting up maintenance pages.
45
+ * Rack::AcceptFormat - Adds a format extension at the end of the URI when there is none, corresponding to the mime-type given in the Accept HTTP header.
46
+ * Rack::HostMeta - Configures /host-meta using a block
47
+ * Rack::Cookies - Adds simple cookie jar hash to env
48
+
49
+ === Use
50
+
51
+ Git is the quickest way to the rack-contrib sources:
52
+
53
+ git clone git://github.com/rack/rack-contrib.git
54
+
55
+ Gems are currently available from GitHub clones:
56
+
57
+ gem install rack-rack-contrib --source=http://gems.github.com/
58
+
59
+ Requiring 'rack/contrib' will add autoloads to the Rack modules for all of the
60
+ components included. The following example shows what a simple rackup
61
+ (+config.ru+) file might look like:
62
+
63
+ require 'rack'
64
+ require 'rack/contrib'
65
+
66
+ use Rack::Profiler if ENV['RACK_ENV'] == 'development'
67
+
68
+ use Rack::ETag
69
+ use Rack::MailExceptions
70
+
71
+ run theapp
72
+
73
+ === Links
74
+
75
+ rack-contrib on GitHub:: <http://github.com/rack/rack-contrib>
76
+ Rack:: <http://rack.rubyforge.org/>
77
+ Rack On GitHub:: <http://github.org/rack/rack>
78
+ rack-devel mailing list:: <http://groups.google.com/group/rack-devel>
data/Rakefile ADDED
@@ -0,0 +1,97 @@
1
+ # Rakefile for Rack::Contrib. -*-ruby-*-
2
+ require 'rake/rdoctask'
3
+ require 'rake/testtask'
4
+
5
+ desc "Run all the tests"
6
+ task :default => [:test]
7
+
8
+ desc "Generate RDox"
9
+ task "RDOX" do
10
+ sh "specrb -Ilib:test -a --rdox >RDOX"
11
+ end
12
+
13
+ desc "Run specs with test/unit style output"
14
+ task :test do
15
+ sh "specrb -Ilib:test -w #{ENV['TEST'] || '-a'} #{ENV['TESTOPTS']}"
16
+ end
17
+
18
+ desc "Run specs with specdoc style output"
19
+ task :spec do
20
+ sh "specrb -Ilib:test -s -w #{ENV['TEST'] || '-a'} #{ENV['TESTOPTS']}"
21
+ end
22
+
23
+ desc "Run all the tests"
24
+ task :fulltest do
25
+ sh "specrb -Ilib:test -w #{ENV['TEST'] || '-a'} #{ENV['TESTOPTS']}"
26
+ end
27
+
28
+ desc "Generate RDoc documentation"
29
+ Rake::RDocTask.new(:rdoc) do |rdoc|
30
+ rdoc.options << '--line-numbers' << '--inline-source' <<
31
+ '--main' << 'README' <<
32
+ '--title' << 'Rack Contrib Documentation' <<
33
+ '--charset' << 'utf-8'
34
+ rdoc.rdoc_dir = "doc"
35
+ rdoc.rdoc_files.include 'README.rdoc'
36
+ rdoc.rdoc_files.include 'RDOX'
37
+ rdoc.rdoc_files.include('lib/rack/*.rb')
38
+ rdoc.rdoc_files.include('lib/rack/*/*.rb')
39
+ end
40
+ task :rdoc => ["RDOX"]
41
+
42
+
43
+ # PACKAGING =================================================================
44
+
45
+ # load gemspec like github's gem builder to surface any SAFE issues.
46
+ require 'rubygems/specification'
47
+ $spec = eval(File.read('tricycle-rack-contrib.gemspec'))
48
+
49
+ def package(ext='')
50
+ "pkg/tricycle-rack-contrib-#{$spec.version}" + ext
51
+ end
52
+
53
+ desc 'Build packages'
54
+ task :package => %w[.gem .tar.gz].map {|e| package(e)}
55
+
56
+ desc 'Build and install as local gem'
57
+ task :install => package('.gem') do
58
+ sh "gem install #{package('.gem')}"
59
+ end
60
+
61
+ directory 'pkg/'
62
+
63
+ file package('.gem') => %w[pkg/ tricycle-rack-contrib.gemspec] + $spec.files do |f|
64
+ sh "gem build tricycle-rack-contrib.gemspec"
65
+ mv File.basename(f.name), f.name
66
+ end
67
+
68
+ file package('.tar.gz') => %w[pkg/] + $spec.files do |f|
69
+ sh "git archive --format=tar HEAD | gzip > #{f.name}"
70
+ end
71
+
72
+ desc 'Publish gem and tarball to rubyforge'
73
+ task 'publish:gem' => [package('.gem'), package('.tar.gz')] do |t|
74
+ sh <<-end
75
+ rubyforge add_release rack tricycle-rack-contrib #{$spec.version} #{package('.gem')} &&
76
+ rubyforge add_file rack tricycle-rack-contrib #{$spec.version} #{package('.tar.gz')}
77
+ end
78
+ end
79
+
80
+ # GEMSPEC ===================================================================
81
+
82
+ file 'tricycle-rack-contrib.gemspec' => FileList['{lib,test}/**','Rakefile', 'README.rdoc'] do |f|
83
+ # read spec file and split out manifest section
84
+ spec = File.read(f.name)
85
+ parts = spec.split(" # = MANIFEST =\n")
86
+ fail 'bad spec' if parts.length != 3
87
+ # determine file list from git ls-files
88
+ files = `git ls-files`.
89
+ split("\n").sort.reject{ |file| file =~ /^\./ }.
90
+ map{ |file| " #{file}" }.join("\n")
91
+ # piece file back together and write...
92
+ parts[1] = " s.files = %w[\n#{files}\n ]\n"
93
+ spec = parts.join(" # = MANIFEST =\n")
94
+ spec.sub!(/s.date = '.*'/, "s.date = '#{Time.now.strftime("%Y-%m-%d")}'")
95
+ File.open(f.name, 'w') { |io| io.write(spec) }
96
+ puts "updated #{f.name}"
97
+ end
@@ -0,0 +1,37 @@
1
+ require 'rack'
2
+
3
+ module Rack
4
+ module Contrib
5
+ def self.release
6
+ "0.9.1"
7
+ end
8
+ end
9
+
10
+ autoload :AcceptFormat, "rack/contrib/accept_format"
11
+ autoload :BounceFavicon, "rack/contrib/bounce_favicon"
12
+ autoload :Cookies, "rack/contrib/cookies"
13
+ autoload :CSSHTTPRequest, "rack/contrib/csshttprequest"
14
+ autoload :Deflect, "rack/contrib/deflect"
15
+ autoload :ETag, "rack/contrib/etag"
16
+ autoload :ExpectationCascade, "rack/contrib/expectation_cascade"
17
+ autoload :GarbageCollector, "rack/contrib/garbagecollector"
18
+ autoload :JSONP, "rack/contrib/jsonp"
19
+ autoload :LighttpdScriptNameFix, "rack/contrib/lighttpd_script_name_fix"
20
+ autoload :Locale, "rack/contrib/locale"
21
+ autoload :MailExceptions, "rack/contrib/mailexceptions"
22
+ autoload :PostBodyContentTypeParser, "rack/contrib/post_body_content_type_parser"
23
+ autoload :ProcTitle, "rack/contrib/proctitle"
24
+ autoload :Profiler, "rack/contrib/profiler"
25
+ autoload :Runtime, "rack/contrib/runtime"
26
+ autoload :Sendfile, "rack/contrib/sendfile"
27
+ autoload :Signals, "rack/contrib/signals"
28
+ autoload :TimeZone, "rack/contrib/time_zone"
29
+ autoload :Evil, "rack/contrib/evil"
30
+ autoload :Callbacks, "rack/contrib/callbacks"
31
+ autoload :NestedParams, "rack/contrib/nested_params"
32
+ autoload :Config, "rack/contrib/config"
33
+ autoload :NotFound, "rack/contrib/not_found"
34
+ autoload :ResponseCache, "rack/contrib/response_cache"
35
+ autoload :RelativeRedirect, "rack/contrib/relative_redirect"
36
+ autoload :StaticCache, "rack/contrib/static_cache"
37
+ end
@@ -0,0 +1,46 @@
1
+ module Rack
2
+ #
3
+ # A Rack middleware for automatically adding a <tt>format</tt> token at the end of the request path
4
+ # when there is none. It can detect formats passed in the HTTP_ACCEPT header to populate this token.
5
+ #
6
+ # e.g.:
7
+ # GET /some/resource HTTP/1.1
8
+ # Accept: application/json
9
+ # ->
10
+ # GET /some/resource.json HTTP/1.1
11
+ # Accept: application/json
12
+ #
13
+ # You can add custom types with this kind of function (taken from sinatra):
14
+ # def mime(ext, type)
15
+ # ext = ".#{ext}" unless ext.to_s[0] == ?.
16
+ # Rack::Mime::MIME_TYPES[ext.to_s] = type
17
+ # end
18
+ # and then:
19
+ # mime :json, 'application/json'
20
+ #
21
+ # Note: it does not take into account multiple media types in the Accept header.
22
+ # The first media type takes precedence over all the others.
23
+ #
24
+ # MIT-License - Cyril Rohr
25
+ #
26
+ class AcceptFormat
27
+
28
+ def initialize(app, default_extention = '.html')
29
+ @ext = default_extention.to_s.strip
30
+ @ext = ".#{@ext}" unless @ext[0] == ?.
31
+ @app = app
32
+ end
33
+
34
+ def call(env)
35
+ req = Rack::Request.new(env)
36
+
37
+ if ::File.extname(req.path_info).empty?
38
+ accept = env['HTTP_ACCEPT'].to_s.scan(/[^;,\s]*\/[^;,\s]*/)[0].to_s
39
+ extension = Rack::Mime::MIME_TYPES.invert[accept] || @ext
40
+ req.path_info = req.path_info+"#{extension}"
41
+ end
42
+
43
+ @app.call(env)
44
+ end
45
+ end
46
+ end
@@ -0,0 +1,20 @@
1
+ module Rack
2
+ class Backstage
3
+ File = ::File
4
+
5
+ def initialize(app, path)
6
+ @app = app
7
+ @file = File.expand_path(path)
8
+ end
9
+
10
+ def call(env)
11
+ if File.exists?(@file)
12
+ content = File.read(@file)
13
+ length = "".respond_to?(:bytesize) ? content.bytesize.to_s : content.size.to_s
14
+ [503, {'Content-Type' => 'text/html', 'Content-Length' => length}, [content]]
15
+ else
16
+ @app.call(env)
17
+ end
18
+ end
19
+ end
20
+ end
@@ -0,0 +1,16 @@
1
+ module Rack
2
+ # Bounce those annoying favicon.ico requests
3
+ class BounceFavicon
4
+ def initialize(app)
5
+ @app = app
6
+ end
7
+
8
+ def call(env)
9
+ if env["PATH_INFO"] == "/favicon.ico"
10
+ [404, {"Content-Type" => "text/html", "Content-Length" => "0"}, []]
11
+ else
12
+ @app.call(env)
13
+ end
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,37 @@
1
+ module Rack
2
+ class Callbacks
3
+ def initialize(&block)
4
+ @before = []
5
+ @after = []
6
+ instance_eval(&block) if block_given?
7
+ end
8
+
9
+ def before(middleware, *args, &block)
10
+ if block_given?
11
+ @before << middleware.new(*args, &block)
12
+ else
13
+ @before << middleware.new(*args)
14
+ end
15
+ end
16
+
17
+ def after(middleware, *args, &block)
18
+ if block_given?
19
+ @after << middleware.new(*args, &block)
20
+ else
21
+ @after << middleware.new(*args)
22
+ end
23
+ end
24
+
25
+ def run(app)
26
+ @app = app
27
+ end
28
+
29
+ def call(env)
30
+ @before.each {|c| c.call(env) }
31
+
32
+ response = @app.call(env)
33
+
34
+ @after.inject(response) {|r, c| c.call(r) }
35
+ end
36
+ end
37
+ end
@@ -0,0 +1,16 @@
1
+ module Rack
2
+
3
+ # Rack::Config modifies the environment using the block given during
4
+ # initialization.
5
+ class Config
6
+ def initialize(app, &block)
7
+ @app = app
8
+ @block = block
9
+ end
10
+
11
+ def call(env)
12
+ @block.call(env)
13
+ @app.call(env)
14
+ end
15
+ end
16
+ end
@@ -0,0 +1,50 @@
1
+ module Rack
2
+ class Cookies
3
+ class CookieJar < Hash
4
+ def initialize(cookies)
5
+ @set_cookies = {}
6
+ @delete_cookies = {}
7
+ super()
8
+ update(cookies)
9
+ end
10
+
11
+ def [](name)
12
+ super(name.to_s)
13
+ end
14
+
15
+ def []=(key, options)
16
+ unless options.is_a?(Hash)
17
+ options = { :value => options }
18
+ end
19
+
20
+ options[:path] ||= '/'
21
+ @set_cookies[key] = options
22
+ super(key.to_s, options[:value])
23
+ end
24
+
25
+ def delete(key, options = {})
26
+ options[:path] ||= '/'
27
+ @delete_cookies[key] = options
28
+ super(key.to_s)
29
+ end
30
+
31
+ def finish!(resp)
32
+ @set_cookies.each { |k, v| resp.set_cookie(k, v) }
33
+ @delete_cookies.each { |k, v| resp.delete_cookie(k, v) }
34
+ end
35
+ end
36
+
37
+ def initialize(app)
38
+ @app = app
39
+ end
40
+
41
+ def call(env)
42
+ req = Request.new(env)
43
+ env['rack.cookies'] = cookies = CookieJar.new(req.cookies)
44
+ status, headers, body = @app.call(env)
45
+ resp = Response.new(body, status, headers)
46
+ cookies.finish!(resp)
47
+ resp.to_a
48
+ end
49
+ end
50
+ end
@@ -0,0 +1,39 @@
1
+ require 'csshttprequest'
2
+
3
+ module Rack
4
+
5
+ # A Rack middleware for providing CSSHTTPRequest responses.
6
+ class CSSHTTPRequest
7
+
8
+ def initialize(app)
9
+ @app = app
10
+ end
11
+
12
+ # Proxies the request to the application then encodes the response with
13
+ # the CSSHTTPRequest encoder
14
+ def call(env)
15
+ status, headers, response = @app.call(env)
16
+ if chr_request?(env)
17
+ response = encode(response)
18
+ modify_headers!(headers, response)
19
+ end
20
+ [status, headers, response]
21
+ end
22
+
23
+ def chr_request?(env)
24
+ env['csshttprequest.chr'] ||=
25
+ !(/\.chr$/.match(env['PATH_INFO'])).nil? || Rack::Request.new(env).params['_format'] == 'chr'
26
+ end
27
+
28
+ def encode(response, assembled_body="")
29
+ response.each { |s| assembled_body << s.to_s } # call down the stack
30
+ return ::CSSHTTPRequest.encode(assembled_body)
31
+ end
32
+
33
+ def modify_headers!(headers, encoded_response)
34
+ headers['Content-Length'] = encoded_response.length.to_s
35
+ headers['Content-Type'] = 'text/css'
36
+ nil
37
+ end
38
+ end
39
+ end