Skip to content

Instantly share code, notes, and snippets.

@RobinDaugherty
Last active October 19, 2022 14:22
Show Gist options
  • Save RobinDaugherty/5e7bc2a6e2369a29c77c to your computer and use it in GitHub Desktop.
Save RobinDaugherty/5e7bc2a6e2369a29c77c to your computer and use it in GitHub Desktop.
ActiveRecord attribute serializer Hashie::Mash stored as JSON in Postgres
class CreateGadgets < ActiveRecord::Migration
def change
create_table "gadgets" do |t|
t.json "info"
end
end
end
class Gadget < ActiveRecord::Base
serialize :info, HashieMashStoredAsJson
# This allows the field to be set as a Hash or anything compatible with it.
def info=(new_value)
self[:info] = HashieMashStoredAsJson.new new_value
end
end
# An ActiveRecord field serializer, presenting as a Mashie::Hash and stored as JSON in postgres.
# Note that since the column type in Postgres is JSON, the value returned by the database
# client is in fact a Hash, which we then encapsulate as a Mashie::Hash. In the other direction, we set
# the column attribute normally by encoding as JSON, which Postgres parses and stores as data.
# Of course, you need to include the hashie gem: https://github.com/intridea/hashie
class HashieMashStoredAsJson < Hashie::Mash
def self.dump(obj)
ActiveSupport::JSON.encode(obj.to_h)
end
def self.load(raw_hash)
new(raw_hash || {})
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment