Created
February 8, 2021 22:41
-
-
Save julik/ebd925a6f71dcc5c306394804637d975 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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