Skip to content

Instantly share code, notes, and snippets.

@alekseyl
Last active May 17, 2018 15:34
Show Gist options
  • Save alekseyl/2bc2bcc6c787b7babee2cedd04d3eca7 to your computer and use it in GitHub Desktop.
Save alekseyl/2bc2bcc6c787b7babee2cedd04d3eca7 to your computer and use it in GitHub Desktop.
JSON compressor example for me-redis gem
module RSmazCompressor
def self.compress(value); RSmaz.compress(value) end
def self.decompress(value); RSmaz.decompress(value) end
end
module ZLibJSONCompressor
def self.compress(value); Zlib.deflate(value.to_json) end
def self.decompress(value); JSON.load( Zlib.inflate( value ) )end
end
# Active record object compressor, but idea is may be used on any object with json representation
module ActiveRecordJSONCompressor
# this is the example, automated for simplicity, if DB schema changes, than cache may broke!!
# in reallife scenario either invalidate cache, or use explicit schemas
# like User: { first_name: 1, last_name: 2 ... }, than your cache will be safer on schema changes.
COMPRESSOR_SCHEMAS = [User, HTag].map{|mdl|
[mdl.to_s, mdl.column_names.each_with_index.map{ |el, i| [el, (20 + i).to_base62] }.to_h]
}.to_h.with_indifferent_access
REVERSE_COMPRESSOR_SCHEMA = COMPRESSOR_SCHEMAS.dup.transform_values(&:invert)
def self.compress( object )
use_schema = COMPRESSOR_SCHEMAS[object.class.to_s]
# _s - shorten for schema, s cannot be used since its a number in Base62 system
Zlib.deflate(
object.serializable_hash
.slice( *use_schema.keys )
.transform_keys{ |k| use_schema[k] }
.reject{ |_,v| v.blank? }
.merge!( _s: object.class.to_s ).to_json
)
end
def self.decompress(value)
compressed_hash = JSON.load( Zlib.inflate(value) )
model = compressed_hash.delete('_s')
schema = REVERSE_COMPRESSOR_SCHEMA[model]
model.constantize.new( compressed_hash.transform_keys{ |k| schema[k] } )
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment