Module: JsonRecord::AttributeMethods
- Included in:
- JsonField
- Defined in:
- lib/json_record/attribute_methods.rb
Overview
Internal methods for reading and writing fields serialized from JSON.
Instance Method Summary collapse
-
#read_attribute(field, context) ⇒ Object
Read a field.
-
#write_attribute(field, val, context) ⇒ Object
Write a field.
Instance Method Details
#read_attribute(field, context) ⇒ Object
Read a field. The field param must be a FieldDefinition and the context should be the record which is being read from.
6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
# File 'lib/json_record/attribute_methods.rb', line 6 def read_attribute (field, context) if field.multivalued? arr = json_attributes[field.name] unless arr arr = EmbeddedDocumentArray.new(field.type, context) json_attributes[field.name] = arr end return arr else val = json_attributes[field.name] if val.nil? and !field.default.nil? val = field.default.dup rescue field.default json_attributes[field.name] = val end return val end end |
#write_attribute(field, val, context) ⇒ Object
Write a field. The field param must be a FieldDefinition and the context should be the record which is being read from.
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 |
# File 'lib/json_record/attribute_methods.rb', line 26 def write_attribute (field, val, context) if field.multivalued? val = val.values if val.is_a?(Hash) json_attributes[field.name] = EmbeddedDocumentArray.new(field.type, context, val) else old_value = read_attribute(field, context) converted_value = field.convert(val) converted_value.parent = context if converted_value.is_a?(EmbeddedDocument) unless old_value == converted_value unless field.type.include?(EmbeddedDocument) or Thread.current[:do_not_track_json_field_changes] changes = changed_attributes if changes.include?(field.name) changes.delete(field.name) if converted_value == changes[field.name] else old_value = (old_value.clone rescue old_value) unless old_value.nil? || old_value.is_a?(Numeric) || old_value.is_a?(Symbol) || old_value.is_a?(TrueClass) || old_value.is_a?(FalseClass) changes[field.name] = old_value end end unless converted_value.nil? json_attributes[field.name] = converted_value else json_attributes.delete(field.name) end end context.json_attributes_before_type_cast[field.name] = val end return val end |