configs
[sinatra.git] / vendor / responder / lib / responder.rb
blob0eef8278adc84022a20bd48ab60ea46a8c3081d8
1 # taken from Cheat
3 # get '/foo/(\w+)'
4 #  ... important code ...
5
6 #   respond_to do |wants|
7 #     wants.html { render :something }
8 #     wants.text { "Just some text." }
9 #     wants.yaml { "Something neat!".to_yaml }
10 #     wants.xml  { "Also, XML.".to_xml }
11 #   end
12 # end
14 module Sinatra
15   module Responder
16     def respond_to
17       yield response = Response.new(request.env["HTTP_ACCEPT"])
18       headers 'Content-Type' => response.content_type
19       body response.body
20     end
22     class Response
23       attr_reader :body, :content_type
24       def initialize(accept) @accept = accept end
26       TYPES = {
27         :yaml => %w[application/yaml text/yaml],
28         :text => %w[text/plain],
29         :html => %w[text/html */* application/html],
30         :xml  => %w[application/xml],
31         :json => %w[application/json]
32       }
34       def method_missing(method, *args)
35         if TYPES[method] && @accept =~ Regexp.union(*TYPES[method])
36           @content_type = TYPES[method].first 
37           @body = yield if block_given?
38         end
39       end
40     end
41   end
42 end