OSDN Git Service

ruby-1.9.1-rc1
[splhack/AndroidRuby.git] / lib / ruby-1.9.1-rc1 / ext / json / lib / json / add / rails.rb
1 # This file contains implementations of rails custom objects for
2 # serialisation/deserialisation.
3
4 unless Object.const_defined?(:JSON) and ::JSON.const_defined?(:JSON_LOADED) and
5   ::JSON::JSON_LOADED
6   require 'json'
7 end
8
9 class Object
10   def self.json_create(object)
11     obj = new
12     for key, value in object
13       next if key == 'json_class'
14       instance_variable_set "@#{key}", value
15     end
16     obj
17   end
18
19   def to_json(*a)
20     result = {
21       'json_class' => self.class.name
22     }
23     instance_variables.inject(result) do |r, name|
24       r[name[1..-1]] = instance_variable_get name
25       r
26     end
27     result.to_json(*a)
28   end
29 end
30
31 class Symbol
32   def to_json(*a)
33     to_s.to_json(*a)
34   end
35 end
36
37 module Enumerable
38   def to_json(*a)
39     to_a.to_json(*a)
40   end
41 end
42
43 # class Regexp
44 #   def to_json(*)
45 #     inspect
46 #   end
47 # end
48 #
49 # The above rails definition has some problems:
50 #
51 # 1. { 'foo' => /bar/ }.to_json # => "{foo: /bar/}"
52 #    This isn't valid JSON, because the regular expression syntax is not
53 #    defined in RFC 4627. (And unquoted strings are disallowed there, too.)
54 #    Though it is valid Javascript.
55 #
56 # 2. { 'foo' => /bar/mix }.to_json # => "{foo: /bar/mix}"
57 #    This isn't even valid Javascript.
58