Permalink
Browse files

Allow callers to send rendering options

This allows for nasty hacks like wrapping json in a textarea to
get iframe transport working in ie7.
  • Loading branch information...
1 parent 07b155f commit 1c9dfdc4ed5c5765116c51231b11bdd443f622cd @travis travis committed Jul 5, 2011
Showing with 53 additions and 3 deletions.
  1. +1 −1 Gemfile.lock
  2. +24 −1 lib/jsend-rails/controller.rb
  3. +1 −1 lib/jsend-rails/version.rb
  4. +27 −0 spec/lib/controller_spec.rb
View
2 Gemfile.lock
@@ -1,7 +1,7 @@
PATH
remote: .
specs:
- jsend-rails (0.9.3)
+ jsend-rails (0.9.4)
rails (~> 3.0)
GEM
View
25 lib/jsend-rails/controller.rb
@@ -1,8 +1,31 @@
module JSend
module Rails
module Controller
+
+ # Render a jsend response
+ #
+ # By default, renders using +render json:+
+ #
+ # If you need to tweak rendering options, for example to render json inside
+ # a <textarea> to fix cranky browsers, pass a :render hash, like:
+ #
+ # +render_jsend {success: {}, render: {as: :text, layout: 'json'}}+
+ #
+ # In the :render, the :as key will be used to control the rendering format.
+ # Any other options will be passed directly to the render call. The example
+ # above will result in the following call to render:
+ #
+ # +render text: {...}, layout: 'json'+
def render_jsend(options_or_status)
- render(:json => Envelope.compute(options_or_status))
+ render_options = if options_or_status.is_a?(Hash)
+ render_options = options_or_status[:render] || {}
+ format = render_options.delete(:as) || :json
+ render_options[format] = Envelope.compute(options_or_status).to_json
+ render_options
+ else
+ {json: Envelope.compute(options_or_status)}
+ end
+ render render_options
end
end
end
View
2 lib/jsend-rails/version.rb
@@ -1,5 +1,5 @@
module JSend
module Rails
- VERSION = "0.9.3"
+ VERSION = "0.9.4"
end
end
View
27 spec/lib/controller_spec.rb
@@ -0,0 +1,27 @@
+require 'spec_helper'
+require 'jsend-rails/controller'
+require 'active_support/all'
+
+describe JSend::Rails::Controller do
+ class C
+ include JSend::Rails::Controller
+ end
+
+ describe "#render_jsend" do
+ let (:c) { C.new }
+ let (:envelope) { {status: :success, result: {}} }
+ before do
+ JSend::Rails::Envelope.should_receive(:compute).and_return(envelope)
+ end
+
+ it "should render json by default" do
+ c.should_receive(:render).with(json: envelope.to_json)
+ c.render_jsend({success: {}})
+ end
+
+ it "should render text if requested" do
+ c.should_receive(:render).with(text: envelope.to_json, layout: true)
+ c.render_jsend({success: {}, render: {as: :text, layout: true}})
+ end
+ end
+end

0 comments on commit 1c9dfdc

Please sign in to comment.