Permalink
Browse files

Add support for bundled OkJson when no other libraries are available

  • Loading branch information...
sstephenson committed Apr 13, 2011
1 parent c2f4140 commit e89093c8d8a2e449ebf774226d3fad0731f573a4
Showing with 625 additions and 3 deletions.
  1. +1 −1 README.rdoc
  2. +3 −1 lib/multi_json.rb
  3. +34 −0 lib/multi_json/engines/okjson.rb
  4. +581 −0 lib/multi_json/vendor/okjson.rb
  5. +6 −1 spec/multi_json_spec.rb
View
@@ -13,7 +13,7 @@ Lots of Ruby libraries utilize JSON parsing in some form, and everyone has their
The <tt>engine</tt> setter takes either a symbol or a class (to allow for custom JSON parsers) that responds to both <tt>.decode</tt> and <tt>.encode</tt> at the class level.
-MultiJSON tries to have intelligent defaulting. That is, if you have any of the supported engines already loaded, it will utilize them before attempting to load any. When loading, libraries are ordered by speed. First Yajl-Ruby, then the JSON gem, then JSON pure.
+MultiJSON tries to have intelligent defaulting. That is, if you have any of the supported engines already loaded, it will utilize them before attempting to load any. When loading, libraries are ordered by speed. First Yajl-Ruby, then the JSON gem, then JSON pure. If no JSON library is available, MultiJSON falls back to a bundled version of <a href="https://github.com/kr/okjson">OkJson</a>.
== Note on Patches/Pull Requests
View
@@ -12,7 +12,8 @@ def engine
REQUIREMENT_MAP = [
["yajl", :yajl],
["json", :json_gem],
- ["json/pure", :json_pure]
+ ["json/pure", :json_pure],
+ ["okjson", :okjson]
]
# The default engine based on what you currently
@@ -38,6 +39,7 @@ def default_engine
#
# * <tt>:json_gem</tt>
# * <tt>:json_pure</tt>
+ # * <tt>:okjson</tt>
# * <tt>:yajl</tt>
def engine=(new_engine)
case new_engine
@@ -0,0 +1,34 @@
+require "multi_json/vendor/okjson" unless defined?(::OkJson)
+
+module MultiJson
+ module Engines
+ class Okjson
+ def self.decode(string, options = {}) #:nodoc:
+ result = OkJson.decode(string)
+ options[:symbolize_keys] ? symbolize_keys(result) : result
+ end
+
+ def self.encode(object) #:nodoc:
+ OkJson.encode(stringify_keys(object))
+ end
+
+ def self.symbolize_keys(object) #:nodoc:
+ return object unless object.is_a?(Hash)
+ object.inject({}) do |result, (key, value)|
+ new_key = key.is_a?(String) ? key.to_sym : key
+ new_value = value.is_a?(Hash) ? symbolize_keys(value) : value
+ result.merge! new_key => new_value
+ end
+ end
+
+ def self.stringify_keys(object) #:nodoc:
+ return object unless object.is_a?(Hash)
+ object.inject({}) do |result, (key, value)|
+ new_key = key.is_a?(Symbol) ? key.to_s : key
+ new_value = value.is_a?(Hash) ? stringify_keys(value) : value
+ result.merge! new_key => new_value
+ end
+ end
+ end
+ end
+end
Oops, something went wrong.

0 comments on commit e89093c

Please sign in to comment.