Browse files

multi-json implementation

  • Loading branch information...
1 parent cf4f566 commit ff66f8042c7509ddda616e2c6ed28c824f2c8a61 @Ortuna Ortuna committed Feb 12, 2013
Showing with 29 additions and 28 deletions.
  1. +2 −0 Gemfile
  2. +2 −0 Gemfile.lock
  3. +23 −28 lib/sinatra/json.rb
  4. +2 −0 spec/json_spec.rb
View
2 Gemfile
@@ -11,6 +11,8 @@ group :development, :test do
platform :ruby do
gem 'yajl-ruby'
end
+
+ gem 'multi_json'
end
# Allows stuff like `tilt=1.2.2 bundle install` or `tilt=master ...`.
View
2 Gemfile.lock
@@ -27,6 +27,7 @@ GEM
eventmachine (0.12.10)
haml (3.1.4)
json (1.6.5)
+ multi_json (1.6.0)
rack (1.4.1)
rack-protection (1.2.0)
rack
@@ -55,6 +56,7 @@ DEPENDENCIES
erubis
haml
json
+ multi_json
rack
rake
rspec (~> 2.3)
View
51 lib/sinatra/json.rb
@@ -90,44 +90,39 @@ module Sinatra
module JSON
class << self
def encode(object)
- enc object, Array, Hash
+ ::MultiJson.dump(object)
end
+ end
- private
+ def json(object, options = {})
+ content_type resolve_content_type(options)
+ resolve_encoder_action object, resolve_encoder(options)
+ end
- def enc(o, *a)
- o = o.to_s if o.is_a? Symbol
- fail "invalid: #{o.inspect}" unless a.empty? or a.include? o.class
- case o
- when Float then o.nan? || o.infinite? ? 'null' : o.inspect
- when TrueClass, FalseClass, Numeric, String then o.inspect
- when NilClass then 'null'
- when Array then map(o, "[%s]") { |e| enc(e) }
- when Hash then map(o, "{%s}") { |k,v| enc(k, String) + ":" + enc(v) }
- end
- end
+ private
- def map(o, wrapper, &block)
- wrapper % o.map(&block).join(',')
- end
+ def resolve_content_type(options = {})
+ options[:content_type] || settings.json_content_type
end
- def json(object, options = {})
- encoder = options[:encoder] || settings.json_encoder
- content_type options[:content_type] || settings.json_content_type
- if encoder.respond_to? :encode then encoder.encode(object)
- elsif encoder.respond_to? :generate then encoder.generate(object)
- elsif encoder.is_a? Symbol then object.__send__(encoder)
- else fail "#{encoder} does not respond to #generate nor #encode"
- end
+ def resolve_encoder(options = {})
+ options[:json_encoder] || settings.json_encoder
end
+
+ def resolve_encoder_action(object = {}, encoder)
+ [:encode, :generate].each do |method|
+ return encoder.send(method, object) if encoder.respond_to? method
+ end
+ if encoder.is_a? Symbol
+ object.__send__(encoder)
+ else
+ fail "#{encoder} does not respond to #generate nor #encode"
+ end
+ end
end
Base.set :json_encoder do
- return Yajl::Encoder if defined? Yajl::Encoder
- return ::JSON if defined? ::JSON
- return :to_json if {}.respond_to? :to_json and [].respond_to? :to_json
- Sinatra::JSON
+ ::MultiJson
end
Base.set :json_content_type, :json
View
2 spec/json_spec.rb
@@ -1,4 +1,6 @@
require 'backports'
+require 'multi_json'
+
require_relative 'spec_helper'
require_relative 'okjson'

0 comments on commit ff66f80

Please sign in to comment.