module Merb # Thanks to Chris Wanstrath # use this in your controllers to switch output based on # the HTTP_ACCEPT header. like so: # respond_to do |type| # type.js { render_js } # type.html { render } # type.xml { @foo.to_xml } # type.yaml { @foo.to_yaml } # end module ResponderMixin def respond_to yield response = Response.new(@env['HTTP_ACCEPT']) @headers['Content-Type'] = response.content_type 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] } 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