Class: Xunch::JsonCodec

Inherits:
Codec
  • Object
show all
Defined in:
lib/xunch/codec/json_codec.rb

Constant Summary

Constants inherited from Codec

Codec::DEFAULT_DATE_FORMAT, Codec::DEFAULT_TYPE_MAP

Instance Method Summary collapse

Constructor Details

#initialize(klass) ⇒ JsonCodec

Returns a new instance of JsonCodec.



4
5
6
7
8
# File 'lib/xunch/codec/json_codec.rb', line 4

def initialize(klass)
  super
  @parser = Yajl::Parser
  @encoder = Yajl::Encoder
end

Instance Method Details

#decode(json_string) ⇒ Object



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
# File 'lib/xunch/codec/json_codec.rb', line 27

def decode(json_string)
  value = @klass.new
  hash = Yajl::Parser.parse(json_string)
  hash.each { |k, v|
    if @type_map.include?(k)
      case @type_map[k]
      when :datetime
        v = DateTime.strptime(v, DEFAULT_DATE_FORMAT)
      when :time
        v = DateTime.strptime(v, DEFAULT_DATE_FORMAT).to_time
      when :bigdecimal
        v = BigDecimal.new(v.to_s)
      else
        # do nothing
      end
    end
    value.send(@set_methods[k],v)
  }
  value
end

#decode_fields(hash, fields) ⇒ Object



59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
# File 'lib/xunch/codec/json_codec.rb', line 59

def decode_fields(hash,fields)
  value = @klass.new
  hash = Yajl::Parser.parse(json_string)
  hash.each { |k, v|
    if @type_map.include?(k)
      case @type_map[k]
      when :datetime
        v = DateTime.strptime(v, DEFAULT_DATE_FORMAT)
      when :time
        v = DateTime.strptime(v, DEFAULT_DATE_FORMAT).to_time
      when :bigdecimal
        v = BigDecimal.new(v.to_s)
      else
        # do nothing
      end
    end
    value.send(@set_methods[k],v)
  }
  value
end

#encode(value) ⇒ Object



10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/xunch/codec/json_codec.rb', line 10

def encode(value)
  unless value.class.name.start_with? @klass.name
    raise XunchCodecError.new("Codec error. Codec class is #{@klass}," <<
      "object_id is #{@klass.object_id}, but value class is #{value.class}," <<
      "object_id is #{value.class.object_id}.
      value class = #{value.class.inspect} vs config class = #{@klass.inspect} ")
  end
  hash = Hash.new
  @get_methods.each do | k , v |
    var_value = value.send(v)
    if var_value != nil
      hash[k] = var_value
    end
  end
  Yajl::Encoder.encode(hash)
end

#encode_fields(value, fields) ⇒ Object



48
49
50
51
52
53
54
55
56
57
# File 'lib/xunch/codec/json_codec.rb', line 48

def encode_fields(value,fields)
  hash = Hash.new
  @get_methods.each do | k , v |
    var_value = value.send(v)
    if var_value != nil
      hash[k] = var_value
    end
  end
  hash
end