Skip to content
This repository has been archived by the owner on May 16, 2021. It is now read-only.

Commit

Permalink
Add Jsonp helper
Browse files Browse the repository at this point in the history
  • Loading branch information
Serg Podtynnyi committed Apr 26, 2011
1 parent 402ace2 commit 910692c
Show file tree
Hide file tree
Showing 3 changed files with 110 additions and 0 deletions.
1 change: 1 addition & 0 deletions lib/sinatra/contrib.rb
Expand Up @@ -23,6 +23,7 @@ module Common
module Custom
# register :Compass
register :Decompile
helpers :Jsonp
end

##
Expand Down
72 changes: 72 additions & 0 deletions lib/sinatra/jsonp.rb
@@ -0,0 +1,72 @@
require 'sinatra/base'
require 'json'

module Sinatra
##
# JSONP output helper for Sinatra. Automatically detects callback params
# and returns proper JSONP output.
# If no callback params where detected it returns plain JSON.
# Works with jQuery jQuery.getJSON method out of the box.
module Jsonp

# Examples

# Classic:

# require "sinatra"
# require "sinatra/jsonp"

# get '/hello' do
# data = ["hello","hi","hallo"]
# JSONP data # JSONP is an alias for jsonp method
# end

# # define your own callback as second string param
# get '/hi' do
# data = ["hello","hi","hallo"]
# jsonp data, 'functionA'
# end

# # same with symbol param
# get '/hallo' do
# data = ["hello","hi","hallo"]
# jsonp data, :functionB
# end

# Modular:

# require "sinatra/base"
# require "sinatra/jsonp"

# class Foo < Sinatra::Base
# helpers Sinatra::Jsonp

# get '/' do
# data = ["hello","hi","hallo"]
# jsonp data
# end
# end
#
def jsonp(*args)
if args.size > 0
data = args[0].to_json
if args.size > 1
callback = args[1].to_s
else
['callback','jscallback','jsonp','jsoncallback'].each do |x|
callback = params.delete(x) unless callback
end
end
if callback
content_type :js
response = "#{callback}(#{data})"
else
response = data
end
response
end
end
alias JSONP jsonp
end
helpers Jsonp
end
37 changes: 37 additions & 0 deletions spec/jsonp_spec.rb
@@ -0,0 +1,37 @@
require "backports"
require_relative 'spec_helper'

describe Sinatra::Jsonp do
before do
mock_app do
helpers Sinatra::Jsonp

get '/method' do
data = ["hello","hi","hallo"]
jsonp data
end
get '/method_with_params' do
data = ["hello","hi","hallo"]
jsonp data, :functionA
end
end
end

it "should return JSON if no callback passed" do
get '/method'
body.should == '["hello","hi","hallo"]'
end
it "should return JSONP if callback passed via GET param" do
get '/method?callback=functionA'
body.should == 'functionA(["hello","hi","hallo"])'
end
it "should return JSONP if callback passed via method param" do
get '/method_with_params'
body.should == 'functionA(["hello","hi","hallo"])'
end
it "should return JSONP with callback passed via method params even if it passed via GET param" do
get '/method_with_params?callback=functionB'
body.should == 'functionA(["hello","hi","hallo"])'
end
end

0 comments on commit 910692c

Please sign in to comment.