Compressed JSON serializer
Compressed JSON is stable, secure, and offen smaller than any other serializers such as Marshal or Bson.
Usage
class Word < ActiveRecord::Base
serialize :payload, CompressedJSON
end
Please note that you should not use update_column on a serialized attribute, which would use to_s rather the serializer to generate SQL.
Upgrade from regluar JSON
If you want to upgrade and migrate your attribute from JSON serializer. You need to clear the attribute first. Because otherwise in the scope of ActiveRecord, the attribute is considered unchanged, and therefore won’t be updated using the new CompressedJSON serializer.
E.g:
Word.find_each { |w| backup = w.payload; w.update_attribute(:payload, []); w.update_attribute(:payload, backup) }
Install
Define CompressedJSON in config/initializers/compressed_json.rb
class CompressedJSON
def self.dump(obj)
ActiveSupport::Gzip.compress(JSON.dump(obj))
end
def self.load(string)
if string
begin
decompressed = ActiveSupport::Gzip.decompress(string)
JSON.load(decompressed)
rescue Zlib::GzipFile::Error
JSON.load(string)
rescue JSON::ParserError
Rails.logger.warn $!.to_s.first(100)
Rails.logger.warn $!.backtrace.join("\n")
nil
end
end
end
end
Native MySQL JSON support?
MySQL 5.7 offers native JSON. I’m not sure if it’s compressed.