Permalink
Browse files

let Sinatra::RespondWith use Sinatra::JSON

  • Loading branch information...
1 parent 6c66bf4 commit 3aa3321583c076887019a5d2e03806ff89cd5551 @rkh committed May 9, 2011
Showing with 20 additions and 8 deletions.
  1. +4 −1 lib/sinatra/respond_with.rb
  2. +16 −7 spec/respond_with_spec.rb
@@ -1,5 +1,5 @@
require 'sinatra/base'
-require 'json' unless Hash.method_defined? :to_json
+require 'sinatra/json'
module Sinatra
##
@@ -125,6 +125,8 @@ def method_missing(meth, *args, &block)
end
module Helpers
+ include Sinatra::JSON
+
def respond_with(template, object = nil, &block)
object, template = template, nil unless Symbol === template
format = Format.new(self)
@@ -142,6 +144,7 @@ def respond_with(template, object = nil, &block)
end
if object
exts.each do |ext|
+ halt json(object) if ext == :json
next unless meth = "to_#{ext}" and object.respond_to? meth
halt(*object.send(meth))
end
@@ -1,5 +1,6 @@
require 'backports'
require_relative 'spec_helper'
+require_relative 'okjson'
describe Sinatra::RespondWith do
def provides(*args)
@@ -161,17 +162,17 @@ def req(*types)
describe "default behavior" do
it 'converts objects to json out of the box' do
respond_with 'a' => 'b'
- req(:json).body.should == {'a' => 'b'}.to_json
+ OkJson.decode(req(:json).body).should == {'a' => 'b'}
end
it 'handles multiple routes correctly' do
respond_app do
get('/') { respond_with 'a' => 'b' }
get('/:name') { respond_with 'a' => params[:name] }
end
- req('/', :json).body.should == {'a' => 'b'}.to_json
- req('/b', :json).body.should == {'a' => 'b'}.to_json
- req('/c', :json).body.should == {'a' => 'c'}.to_json
+ OkJson.decode(req('/', :json).body).should == {'a' => 'b'}
+ OkJson.decode(req('/b', :json).body).should == {'a' => 'b'}
+ OkJson.decode(req('/c', :json).body).should == {'a' => 'c'}
end
it "calls to_EXT if available" do
@@ -206,17 +207,25 @@ def req(*types)
body.should be_empty
end
- it 'falls back to to_EXT if no template is found' do
+ it 'falls back to #json if no template is found' do
respond_with :foo, :name => 'World'
req(:json).should be_ok
- body.should == {:name => 'World'}.to_json
+ OkJson.decode(body).should == {'name' => 'World'}
end
- it 'favors templates over to_EXT' do
+ it 'favors templates over #json' do
respond_with :bar, :name => 'World'
req(:json).should be_ok
body.should == 'json!'
end
+
+ it 'falls back to to_EXT if no template is found' do
+ object = {:name => 'World'}
+ def object.to_pdf; "hi" end
+ respond_with :foo, object
+ req(:pdf).should be_ok
+ body.should == "hi"
+ end
end
describe 'customizing' do

0 comments on commit 3aa3321

Please sign in to comment.