Class: JsonRecord::JsonField

Inherits:
Object
  • Object
show all
Includes:
AttributeMethods
Defined in:
lib/json_record/json_field.rb

Instance Method Summary collapse

Methods included from AttributeMethods

#read_attribute, #write_attribute

Constructor Details

#initialize(record, name, schemas) ⇒ JsonField

Returns a new instance of JsonField.

Raises:

  • (ArgumentError)

7
8
9
10
11
12
13
14
15
# File 'lib/json_record/json_field.rb', line 7

def initialize (record, name, schemas)
  @record = record
  @name = name.to_s
  @schemas = schemas
  @attributes = nil
  json_column = record.class.columns_hash[@name]
  raise ArgumentError.new("column #{name} does not exist in #{table_name}") unless json_column
  @compressed = json_column.type == :binary
end

Instance Method Details

#changed_attributesObject


67
68
69
# File 'lib/json_record/json_field.rb', line 67

def changed_attributes
  @record.instance_variable_get(:@changed_attributes)
end

#changesObject


63
64
65
# File 'lib/json_record/json_field.rb', line 63

def changes
  @record.changes
end

#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

#json_attributesObject


58
59
60
61
# File 'lib/json_record/json_field.rb', line 58

def json_attributes
  deserialize unless @attributes
  @attributes
end

#serializeObject


17
18
19
20
21
22
23
24
25
# File 'lib/json_record/json_field.rb', line 17

def serialize
  if @attributes
    stripped_attributes = {}
    @attributes.each_pair{|k, v| stripped_attributes[k] = v unless v.blank?}
    json = stripped_attributes.to_json
    json = Zlib::Deflate.deflate(json) if json and @compressed
    @record[@name] = json
  end
end