Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
blake.mizerany@gmail.com
committed
Sep 14, 2007
1 parent
0cfd1b7
commit 33fea0f
Showing
2 changed files
with
45 additions
and
0 deletions.
There are no files selected for viewing
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
Original file line number | Original file line | Diff line number | Diff line change |
---|---|---|---|
@@ -0,0 +1,3 @@ | |||
require File.dirname(__FILE__) + '/lib/responder' | |||
|
|||
Sinatra::EventContext.send(:include, Sinatra::Responder) |
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
Original file line number | Original file line | Diff line number | Diff line change |
---|---|---|---|
@@ -0,0 +1,42 @@ | |||
# taken from Cheat | |||
|
|||
# get '/foo/(\w+)' | |||
# ... important code ... | |||
# | |||
# respond_to do |wants| | |||
# wants.html { render :something } | |||
# wants.text { "Just some text." } | |||
# wants.yaml { "Something neat!".to_yaml } | |||
# wants.xml { "Also, XML.".to_xml } | |||
# end | |||
# end | |||
|
|||
module Sinatra | |||
module Responder | |||
def respond_to | |||
yield response = Response.new(request.env["HTTP_ACCEPT"]) | |||
headers 'Content-Type' => response.content_type | |||
body response.body | |||
end | |||
|
|||
class Response | |||
attr_reader :body, :content_type | |||
def initialize(accept) @accept = accept end | |||
|
|||
TYPES = { | |||
:yaml => %w[application/yaml text/yaml], | |||
:text => %w[text/plain], | |||
:html => %w[text/html */* application/html], | |||
:xml => %w[application/xml], | |||
:json => %w[application/json] | |||
} | |||
|
|||
def method_missing(method, *args) | |||
if TYPES[method] && @accept =~ Regexp.union(*TYPES[method]) | |||
@content_type = TYPES[method].first | |||
@body = yield if block_given? | |||
end | |||
end | |||
end | |||
end | |||
end |