Sha256: 8cde8339a1a2a08e4d37a4642a62ded65b26e743a905a389d791edac4d5c6d4e

Contents?: true

Size: 1022 Bytes

Versions: 1

Compression:

Stored size: 1022 Bytes

Contents

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  

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
merb-0.0.7 lib/merb/mixins/responder_mixin.rb