Skip to content

Instantly share code, notes, and snippets.

@dpaluy
Created December 25, 2019 08:32
Show Gist options
  • Select an option

  • Save dpaluy/ca72531037aaa36e052c2d9f24fd6267 to your computer and use it in GitHub Desktop.

Select an option

Save dpaluy/ca72531037aaa36e052c2d9f24fd6267 to your computer and use it in GitHub Desktop.
store large JSON in PostgreSQL with Rails Attributes API
# app/types/binary_hash.rb
class BinaryHash < ActiveRecord::Type::Binary
def serialize(value)
super value_to_binary(value.to_json)
end
def deserialize(value)
super case value
when NilClass
{}
when ActiveModel::Type::Binary::Data
value_to_hash(value.to_s)
else
value_to_hash(PG::Connection.unescape_bytea(value))
end
end
private
def value_to_hash(value)
JSON.parse(
ActiveSupport::Gzip.decompress(value),
symbolize_names: true
) || {}
end
add_column :reports, :data, :binary
# app/models/report.rb
class Report < ApplicationRecord
attribute :data, :binary_hash
end
# config/initializers/types.rb
ActiveRecord::Type.register(:binary_hash, BinaryHash)
@dpaluy
Copy link
Author

dpaluy commented Dec 25, 2019

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment