From 42596543dc0bac7aad9763b82ee4cc2b17f3110c Mon Sep 17 00:00:00 2001 From: Jeremy Kemper Date: Wed, 6 Dec 2006 22:27:08 +0000 Subject: respond_to recognizes JSON. render :json => @person.to_json automatically sets the content type and takes a :callback option to specify a client-side function to call using the rendered JSON as an argument. References #4185. git-svn-id: http://svn-commit.rubyonrails.org/rails/trunk@5694 5ecf4fe2-1ee6-0310-87b1-e25e094e27de --- actionpack/lib/action_controller/base.rb | 32 ++++++++++++++++++++++++++++++++ 1 file changed, 32 insertions(+) (limited to 'actionpack/lib/action_controller/base.rb') diff --git a/actionpack/lib/action_controller/base.rb b/actionpack/lib/action_controller/base.rb index 31016a47c5..cbf34e9742 100755 --- a/actionpack/lib/action_controller/base.rb +++ b/actionpack/lib/action_controller/base.rb @@ -650,6 +650,20 @@ module ActionController #:nodoc: # # _Deprecation_ _notice_: This used to have the signature render_text("text", status = 200) # + # === Rendering JSON + # + # Rendering JSON sets the content type to text/x-json and optionally wraps the JSON in a callback. It is expected + # that the response will be eval'd for use as a data structure. + # + # # Renders '{name: "David"}' + # render :json => {:name => "David"}.to_json + # + # Sometimes the result isn't handled directly by a script (such as when the request comes from a SCRIPT tag), + # so the callback option is provided for these cases. + # + # # Renders 'show({name: "David"})' + # render :json => {:name => "David"}.to_json, :callback => 'show' + # # === Rendering an inline template # # Rendering of an inline template works as a cross between text and action rendering where the source for the template @@ -733,6 +747,12 @@ module ActionController #:nodoc: elsif xml = options[:xml] render_xml(xml, options[:status]) + + elsif json = options[:json] + render_json(json, options[:callback], options[:status]) + + elsif yaml = options[:yaml] + render_yaml(yaml, options[:status]) elsif partial = options[:partial] partial = default_template_name if partial == true @@ -813,6 +833,18 @@ module ActionController #:nodoc: response.content_type = Mime::XML render_text(xml, status) end + + def render_json(json, callback = nil, status = nil) #:nodoc: + json = "#{callback}(#{json})" unless callback.blank? + + response.content_type = Mime::JSON + render_text(json, status) + end + + def render_yaml(yaml, status = nil) #:nodoc: + response.content_type = Mime::YAML + render_text(yaml, status) + end def render_nothing(status = nil) #:nodoc: render_text(' ', status) -- cgit v1.2.3