Sha256: 91e2fd4d6944ba4a93345d3d50cf55ce63d1e65ced6d8f57026959b5b3db3534

Contents?: true

Size: 1.01 KB

Versions: 2

Compression:

Stored size: 1.01 KB

Contents

module Martinet
  class ActiveRecordSerializer
    def self.serialize(record:)
      return record unless serializable?(record: record)
      { klass: record.class.name, record_id: record.id }
    end

    def self.deserialize(object_hash:)
      record_for(object_hash: object_hash) || object_hash
    end

    def self.record_for(object_hash:)
      return unless deserializable?(object_hash: object_hash)

      record_klass = object_hash[:klass].safe_constantize
      record_klass.find_by(id: object_hash[:record_id])
    end

    # FIXME: Refactor this method
    def self.serializable?(record:)
      record.respond_to?(:id) && record.id.presence && record.class.respond_to?(:find_by)
    end

    # FIXME: Refactor this method, maybe a rescue block?
    def self.deserializable?(object_hash:)
      valid = [:klass, :record_id].all? do |k|
        object_hash.respond_to?(:key) && object_hash.key?(k) && object_hash[k].presence
      end
      valid && object_hash[:klass].safe_constantize.respond_to?(:find_by)
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
martinet-0.0.3 lib/martinet/active_record_serializer.rb
martinet-0.0.2 lib/martinet/active_record_serializer.rb