1unless defined?(::JSON::JSON_LOADED) and ::JSON::JSON_LOADED
2  require 'json'
3end
4require 'date'
5
6# DateTime serialization/deserialization
7class DateTime
8
9  # Deserializes JSON string by converting year <tt>y</tt>, month <tt>m</tt>,
10  # day <tt>d</tt>, hour <tt>H</tt>, minute <tt>M</tt>, second <tt>S</tt>,
11  # offset <tt>of</tt> and Day of Calendar Reform <tt>sg</tt> to DateTime.
12  def self.json_create(object)
13    args = object.values_at('y', 'm', 'd', 'H', 'M', 'S')
14    of_a, of_b = object['of'].split('/')
15    if of_b and of_b != '0'
16      args << Rational(of_a.to_i, of_b.to_i)
17    else
18      args << of_a
19    end
20    args << object['sg']
21    civil(*args)
22  end
23
24  alias start sg unless method_defined?(:start)
25
26  # Returns a hash, that will be turned into a JSON object and represent this
27  # object.
28  def as_json(*)
29    {
30      JSON.create_id => self.class.name,
31      'y' => year,
32      'm' => month,
33      'd' => day,
34      'H' => hour,
35      'M' => min,
36      'S' => sec,
37      'of' => offset.to_s,
38      'sg' => start,
39    }
40  end
41
42  # Stores class name (DateTime) with Julian year <tt>y</tt>, month <tt>m</tt>,
43  # day <tt>d</tt>, hour <tt>H</tt>, minute <tt>M</tt>, second <tt>S</tt>,
44  # offset <tt>of</tt> and Day of Calendar Reform <tt>sg</tt> as JSON string
45  def to_json(*args)
46    as_json.to_json(*args)
47  end
48end
49
50
51