Skip to content

Instantly share code, notes, and snippets.

@jarthod

jarthod/compressed.rb

Forked from romanbsd/compressed.rb
Last active Jul 22, 2020
Embed
What would you like to do?
Compressed fields in Mongoid 6.4
require 'zlib'
class CompressedString < String
def mongoize
BSON::Binary.new(Zlib::Deflate.deflate(self))
end
class << self
# Get the object as it was stored in the database, and instantiate
# this custom class from it.
def demongoize(object)
case object
when BSON::Binary then CompressedString.new(Zlib::Inflate.inflate(object.data))
when String then CompressedString.new(object)
else object
end
end
# Takes any possible object and converts it to how it would be
# stored in the database.
def mongoize(object)
case object
when CompressedString then object.mongoize
when String then CompressedString.new(object).mongoize
else object
end
end
# Converts the object that was supplied to a criteria and converts it
# into a database friendly form.
alias_method :evolve, :mongoize
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment