Class: MotionRecord::Serialization::JSONSerializer

Inherits:
BaseSerializer show all
Defined in:
lib/motion_record/serialization/json_serializer.rb

Class Method Summary collapse

Instance Method Summary collapse

Methods inherited from BaseSerializer

#initialize

Constructor Details

This class inherits a constructor from MotionRecord::Serialization::BaseSerializer

Class Method Details

.generate_json(obj) ⇒ Object

JSON generate/parse code is hoisted from BubbleWrap::JSON



23
24
25
# File 'lib/motion_record/serialization/json_serializer.rb', line 23

def self.generate_json(obj)
  NSJSONSerialization.dataWithJSONObject(obj, options:0, error:nil).to_str
end

.parse_json(str_data) ⇒ Object

Raises:



27
28
29
30
31
32
33
34
35
# File 'lib/motion_record/serialization/json_serializer.rb', line 27

def self.parse_json(str_data)
  return nil unless str_data
  data = str_data.respond_to?('dataUsingEncoding:') ? str_data.dataUsingEncoding(NSUTF8StringEncoding) : str_data
  opts = NSJSONReadingMutableContainers | NSJSONReadingMutableLeaves | NSJSONReadingAllowFragments
  error = Pointer.new(:id)
  obj = NSJSONSerialization.JSONObjectWithData(data, options:opts, error:error)
  raise JSONParserError, error[0].description if error[0]
  obj
end

Instance Method Details

#deserialize(value) ⇒ Object



14
15
16
17
18
19
# File 'lib/motion_record/serialization/json_serializer.rb', line 14

def deserialize(value)
  unless @column.type == :text
    raise "JSON can only be deserialized from TEXT columns"
  end
  self.class.parse_json(value)
end

#serialize(value) ⇒ Object



7
8
9
10
11
12
# File 'lib/motion_record/serialization/json_serializer.rb', line 7

def serialize(value)
  unless @column.type == :text
    raise "JSON can only be serialized to TEXT columns"
  end
  self.class.generate_json(value)
end