Skip to content

Instantly share code, notes, and snippets.

@joeldrapper
Last active July 12, 2023 12:58
Show Gist options
  • Save joeldrapper/59ed8cb53a0ed91e031384c7b8efa073 to your computer and use it in GitHub Desktop.
Save joeldrapper/59ed8cb53a0ed91e031384c7b8efa073 to your computer and use it in GitHub Desktop.
Paquito Job Packer
# frozen_string_literal: true
module Packer
# A special packer class for globally identifiable objects. It takes a global ID and packs it as a String, then rehydrates it as a GlobalID lookup.
class GloballyIdentifiable
def self.from_pack(uri)
GlobalID::Locator.locate(uri)
end
def initialize(identifiable)
@global_id = identifiable.to_global_id
end
def as_pack
@global_id.to_s
end
end
module_function
Codec = Paquito::SingleBytePrefixVersionWithStringBypass.new(
0, # default version
{
0 => Paquito::CodecFactory.build(
[
Symbol,
Set,
Time,
Date,
BigDecimal,
ActiveRecord::Base,
ActiveSupport::HashWithIndifferentAccess,
ActiveSupport::TimeWithZone
],
serializable_type: true
)
},
Paquito::ConditionalCompressor.new(Zlib, 1024)
)
def dump(object)
case object
# For the purpose of this packer, if the object can be identified by a GlobalID, we only want to store the GlobalID.
# This is useful for jobs, but we wouldn't want this with a cache.
when GlobalID::Identification
object = GloballyIdentifiable.new(object)
end
Base64.encode64(
Codec.dump(object)
)
end
def load(data)
Codec.load(
Base64.decode64(data)
)
end
end
# Patch Range to make it packable
class Range
def self.from_pack(args)
new(*args)
end
def as_pack
[self.begin, self.end, exclude_end?]
end
end
# Patch GlobalID to make it packable
class GlobalID
def self.from_pack(uri)
new(uri)
end
alias_method :as_pack, :to_s
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment