Method: JsonRecord::JsonField#deserialize

Defined in:
lib/json_record/json_field.rb

#deserializeObject



27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/json_record/json_field.rb', line 27

def deserialize
  @attributes = {}
  @schemas.each do |schema|
    schema.fields.values.each do |field|
      @attributes[field.name] = field.multivalued? ? EmbeddedDocumentArray.new(field.type, @record) : field.default
    end
  end
  
  unless @record[@name].blank?
    json = @record[@name]
    json = Zlib::Inflate.inflate(json) if @compressed
    do_not_track_changes = Thread.current[:do_not_track_json_field_changes]
    Thread.current[:do_not_track_json_field_changes] = true
    begin
      ActiveSupport::JSON.decode(json).each_pair do |attr_name, attr_value|
        setter = "#{attr_name}=".to_sym
        if @record.respond_to?(setter)
          @record.send(setter, attr_value)
        else
          field = nil
          @schemas.each{|schema| field = schema.fields[attr_name]; break if field}
          field = FieldDefinition.new(attr_name, :type => attr_value.class) unless field
          write_attribute(field, attr_value, @record)
        end
      end
    ensure
      Thread.current[:do_not_track_json_field_changes] = do_not_track_changes
    end
  end
end