Last active
October 19, 2022 14:22
-
-
Save RobinDaugherty/5e7bc2a6e2369a29c77c to your computer and use it in GitHub Desktop.
ActiveRecord attribute serializer Hashie::Mash stored as JSON in Postgres
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
class CreateGadgets < ActiveRecord::Migration | |
def change | |
create_table "gadgets" do |t| | |
t.json "info" | |
end | |
end | |
end |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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