ActiveRecord::Coders

Library that provides a set of serializers and a pipeline for optionally chaining them.

Installation

Add this line to your application's Gemfile:

gem "activerecord-coders"

Usage

Here follows a list of various serializers, compressors and encryptors.

Serializers

Serializers allow you to serialize Ruby objects to text/binary format in order to store more complex data structures in a single column.

Marshal

Store as binary (t.binary :info)

class User < ActiveRecord::Base
  serialize :info, Coders::Seralizers::Marshal.new
end

YAML

Store as text (t.text :info)

class User < ActiveRecord::Base
  serialize :info, Coders::Seralizers::YAML.new
end

JSON

Store as text (t.text :info)

class User < ActiveRecord::Base
  serialize :info, Coders::Seralizers::JSON.new
end

Store as binary (t.binary :info)

MessagePack

class User < ActiveRecord::Base
  serialize :info, Coders::Seralizers::MessagePack.new
end

Compressors

Compressors allow you to compress raw text, or serialized Ruby objects to more efficiently store your data.

Gzip

Store as binary (t.binary)

class User < ActiveRecord::Base
  serialize :info, Coders::Compressors::Gzip.new
end

Encryptors

Encryptors allow you to encrypt text/binary/serialized Ruby objects to more securely store your data.

AES

Store as binary (t.binary)

class User < ActiveRecord::Base
  serialize :info, Coders::Encryptors::AES.new(ENV["CIPHER_KEY"])
end

Arguments you can pass to Coders::Encryptors::AES.new:

  • password [String] required
  • key_length [Integer] optional, default: 256
  • options [Hash] optional
    • :binary optional, default: true

Pipeline

You can chain together multiple coders to combine their operations for a single attribute.

Serialize -> Compress -> Encrypt

Store as binary (t.binary)

class User < ActiveRecord::Base
  serialize :info, Coders::Pipeline.new(
    Coders::Serializers::MessagePack.new,
    Coders::Compressors::Gzip.new,
    Coders::Encryptors::AES.new(ENV["CIPHER"])
  )
end

User.create(info: { cc: "0000-0000-0000-0000" })

The above example will execute each coder in the defined order. The { cc: "0000-0000-0000-0000 } Hash will be serialized to binary with MessagePack, then it'll be compressed with Gzip, and finally encrypted with AES (256), before being stored.

Contributing

  • Requirements:
    • Code style must match that of the project
    • Avoid including libraries that have dependencies
    • 100% test coverage with SimpleCov

License

Released under the MIT license. See LICENSE.