Skip to content
This repository
tree: 52798fd479
Fetching contributors…

Cannot retrieve contributors at this time

file 103 lines (86 sloc) 2.529 kb
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103
module ActionController
  module RenderOptions
    extend ActiveSupport::Concern

    included do
      extlib_inheritable_accessor :_renderers
      self._renderers = []
    end

    module ClassMethods
      def _write_render_options
        renderers = _renderers.map do |r|
          <<-RUBY_EVAL
if options.key?(:#{r})
_process_options(options)
return _render_#{r}(options[:#{r}], options)
end
RUBY_EVAL
        end

        class_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1
def _handle_render_options(options)
#{renderers.join}
end
RUBY_EVAL
      end

      def _add_render_option(name)
        _renderers << name
        _write_render_options
      end
    end

    def render_to_body(options)
      _handle_render_options(options) || super
    end
  end

  module RenderOption #:nodoc:
    def self.extended(base)
      base.extend ActiveSupport::Concern
      base.send :include, ::ActionController::RenderOptions

      def base.register_renderer(name)
        included { _add_render_option(name) }
      end
    end
  end

  module Renderers
    module Json
      extend RenderOption
      register_renderer :json

      def _render_json(json, options)
        json = ActiveSupport::JSON.encode(json) unless json.respond_to?(:to_str)
        json = "#{options[:callback]}(#{json})" unless options[:callback].blank?
        self.content_type ||= Mime::JSON
        self.response_body = json
      end
    end

    module Js
      extend RenderOption
      register_renderer :js

      def _render_js(js, options)
        self.content_type ||= Mime::JS
        self.response_body = js
      end
    end

    module Xml
      extend RenderOption
      register_renderer :xml

      def _render_xml(xml, options)
        self.content_type ||= Mime::XML
        self.response_body = xml.respond_to?(:to_xml) ? xml.to_xml : xml
      end
    end

    module RJS
      extend RenderOption
      register_renderer :update

      def _render_update(proc, options)
        generator = ActionView::Helpers::PrototypeHelper::JavaScriptGenerator.new(view_context, &proc)
        self.content_type = Mime::JS
        self.response_body = generator.to_s
      end
    end

    module All
      extend ActiveSupport::Concern

      include ActionController::Renderers::Json
      include ActionController::Renderers::Js
      include ActionController::Renderers::Xml
      include ActionController::Renderers::RJS
    end
  end
end
Something went wrong with that request. Please try again.