Class: LiveComponent::ModelSerializer

Inherits:
Object
  • Object
show all
Defined in:
lib/live_component/model_serializer.rb

Constant Summary collapse

MODEL_SERIALIZER_KEY =
"_lc_ar".freeze

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(sign: true, reload: false, attributes: true) ⇒ ModelSerializer

Returns a new instance of ModelSerializer.



16
17
18
19
20
# File 'lib/live_component/model_serializer.rb', line 16

def initialize(sign: true, reload: false, attributes: true)
  @sign = sign
  @reload = reload
  @attributes = attributes.is_a?(Array) ? attributes.map(&:to_s) : attributes
end

Instance Attribute Details

#attributesObject (readonly)

Returns the value of attribute attributes.



7
8
9
# File 'lib/live_component/model_serializer.rb', line 7

def attributes
  @attributes
end

#reloadObject (readonly) Also known as: reload?

Returns the value of attribute reload.



7
8
9
# File 'lib/live_component/model_serializer.rb', line 7

def reload
  @reload
end

#signObject (readonly) Also known as: sign?

Returns the value of attribute sign.



7
8
9
# File 'lib/live_component/model_serializer.rb', line 7

def sign
  @sign
end

Class Method Details

.makeObject



12
13
14
# File 'lib/live_component/model_serializer.rb', line 12

def self.make(...)
  new(...)
end

Instance Method Details

#deserialize(hash) ⇒ Object



49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
# File 'lib/live_component/model_serializer.rb', line 49

def deserialize(hash)
  gid_attrs = hash[MODEL_SERIALIZER_KEY]
  gid = gid_attrs["gid"]
  signed = gid_attrs["signed"]

  if reload?
    if signed
      GlobalID::Locator.locate_signed(gid)
    else
      GlobalID::Locator.locate(gid)
    end
  else
    parsed_gid = signed ? SignedGlobalID.parse(gid) : GlobalID.parse(gid)
    RecordProxy.for(parsed_gid, hash.except("_lc_ar"))
  end
end

#serialize(object) ⇒ Object



22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
# File 'lib/live_component/model_serializer.rb', line 22

def serialize(object)
  gid = sign? ? object.to_signed_global_id : object.to_global_id

  { MODEL_SERIALIZER_KEY => { "gid" => gid.to_s, "signed" => sign? } }.tap do |result|
    object_attributes = if object.is_a?(RecordProxy)
      object.cached_attributes
    else
      object.attributes
    end

    attributes_hash = if attributes.is_a?(Array)
      object_attributes.slice(*attributes)
    elsif attributes  # true case
      object_attributes
    end

    if attributes_hash
      attributes_hash.each_pair do |k, v|
        result[k] = LiveComponent.serializer.serialize(v)
      end
    end
  end
rescue URI::GID::MissingModelIdError
  raise SerializationError, "Unable to serialize #{object.class} " \
    "without an id. (Maybe you forgot to call save?)"
end