Skip to content

Instantly share code, notes, and snippets.

@julik
Created February 8, 2021 22:41
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save julik/ebd925a6f71dcc5c306394804637d975 to your computer and use it in GitHub Desktop.
Save julik/ebd925a6f71dcc5c306394804637d975 to your computer and use it in GitHub Desktop.
# In a couple of tables we have VARBINARY columns which either encode a packed
# integer of some kind, or a checksum (which is commonly shared as a hexadecimal).
# This module allows rapid definition of such columns and accessors for them. For example,
# imagine you want to store a CRC32 value - which fits into a uint4
#
# class RecordWithChecksum < ActiveRecord::Base
# extend PackedColumn
# packed_value_column :crc32, pattern: 'V'
# end
#
# # This will set the `crc32` column to the encoded value:
# record.crc32 = Zlib.crc32(some_payload)
#
# The column you create must be BLOB, BINARY or VARBINARY type.
module PackedColumn
class SingleValuePackCoder < Struct.new(:pattern)
def dump(value)
value ? [value].pack(pattern) : nil
end
def load(bin_str)
bin_str ? bin_str.unpack(pattern).first : nil
end
end
def packed_value_column(column, pattern:)
serialize column.to_s, SingleValuePackCoder.new(pattern.to_s)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment