Skip to content

Commit

Permalink
Add support for bundled OkJson when no other libraries are available
Browse files Browse the repository at this point in the history
  • Loading branch information
sstephenson committed Apr 13, 2011
1 parent c2f4140 commit e89093c
Show file tree
Hide file tree
Showing 5 changed files with 625 additions and 3 deletions.
2 changes: 1 addition & 1 deletion README.rdoc
Expand Up @@ -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

Expand Down
4 changes: 3 additions & 1 deletion lib/multi_json.rb
Expand Up @@ -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
Expand All @@ -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
Expand Down
34 changes: 34 additions & 0 deletions lib/multi_json/engines/okjson.rb
@@ -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

0 comments on commit e89093c

Please sign in to comment.