Class: JsonRecord::JsonField
- Inherits:
-
Object
- Object
- JsonRecord::JsonField
show all
- Includes:
- AttributeMethods
- Defined in:
- lib/json_record/json_field.rb
Instance Method Summary
collapse
#read_attribute, #write_attribute
Constructor Details
#initialize(record, name, schemas) ⇒ JsonField
Returns a new instance of JsonField.
7
8
9
10
11
12
13
|
# File 'lib/json_record/json_field.rb', line 7
def initialize (record, name, schemas)
@record = record
@name = name
@schemas = schemas
@attributes = nil
@compressed = record.class.columns_hash[name].type == :binary
end
|
Instance Method Details
#changed_attributes ⇒ Object
65
66
67
|
# File 'lib/json_record/json_field.rb', line 65
def changed_attributes
@record.send(:changed_attributes)
end
|
#changes ⇒ Object
61
62
63
|
# File 'lib/json_record/json_field.rb', line 61
def changes
@record.changes
end
|
#deserialize ⇒ Object
25
26
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
|
# File 'lib/json_record/json_field.rb', line 25
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_attributes ⇒ Object
56
57
58
59
|
# File 'lib/json_record/json_field.rb', line 56
def json_attributes
deserialize unless @attributes
@attributes
end
|
#serialize ⇒ Object
15
16
17
18
19
20
21
22
23
|
# File 'lib/json_record/json_field.rb', line 15
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
|