summaryrefslogtreecommitdiff
path: root/ext/json/lib/json/add/rails.rb
diff options
context:
space:
mode:
authornaruse <naruse@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2007-12-04 08:09:44 +0000
committernaruse <naruse@b2dd03c8-39d4-4d8f-98ff-823fe69b080e>2007-12-04 08:09:44 +0000
commit825ce503c0e52edb944def195be0d3d55e3e71b3 (patch)
treefce260b670515f356a94d399fe97853b65ae1268 /ext/json/lib/json/add/rails.rb
parent86f1cff0eb8fa3c4d5925fb8fe5eac31a323bb84 (diff)
* lib/json.rb, lib/json/*: moved to ext/json/lib.
-- M trunk/ChangeLog D trunk/lib/json D trunk/lib/json.rb A trunk/ext/json/lib A trunk/ext/json/lib/json A trunk/ext/json/lib/json.rb A trunk/ext/json/extconf.rb git-svn-id: svn+ssh://ci.ruby-lang.org/ruby/trunk@14100 b2dd03c8-39d4-4d8f-98ff-823fe69b080e
Diffstat (limited to 'ext/json/lib/json/add/rails.rb')
-rw-r--r--ext/json/lib/json/add/rails.rb58
1 files changed, 58 insertions, 0 deletions
diff --git a/ext/json/lib/json/add/rails.rb b/ext/json/lib/json/add/rails.rb
new file mode 100644
index 0000000000..e86ed1aab9
--- /dev/null
+++ b/ext/json/lib/json/add/rails.rb
@@ -0,0 +1,58 @@
+# This file contains implementations of rails custom objects for
+# serialisation/deserialisation.
+
+unless Object.const_defined?(:JSON) and ::JSON.const_defined?(:JSON_LOADED) and
+ ::JSON::JSON_LOADED
+ require 'json'
+end
+
+class Object
+ def self.json_create(object)
+ obj = new
+ for key, value in object
+ next if key == 'json_class'
+ instance_variable_set "@#{key}", value
+ end
+ obj
+ end
+
+ def to_json(*a)
+ result = {
+ 'json_class' => self.class.name
+ }
+ instance_variables.inject(result) do |r, name|
+ r[name[1..-1]] = instance_variable_get name
+ r
+ end
+ result.to_json(*a)
+ end
+end
+
+class Symbol
+ def to_json(*a)
+ to_s.to_json(*a)
+ end
+end
+
+module Enumerable
+ def to_json(*a)
+ to_a.to_json(*a)
+ end
+end
+
+# class Regexp
+# def to_json(*)
+# inspect
+# end
+# end
+#
+# The above rails definition has some problems:
+#
+# 1. { 'foo' => /bar/ }.to_json # => "{foo: /bar/}"
+# This isn't valid JSON, because the regular expression syntax is not
+# defined in RFC 4627. (And unquoted strings are disallowed there, too.)
+# Though it is valid Javascript.
+#
+# 2. { 'foo' => /bar/mix }.to_json # => "{foo: /bar/mix}"
+# This isn't even valid Javascript.
+