Skip to content

Instantly share code, notes, and snippets.

@RobinDaugherty
Created February 1, 2016 04:20
Show Gist options
  • Save RobinDaugherty/bafe6716b984f8bcc87e to your computer and use it in GitHub Desktop.
Save RobinDaugherty/bafe6716b984f8bcc87e to your computer and use it in GitHub Desktop.
ActiveRecord attribute serializer Hashie::Mash stored as a JSON string in Postgres
class CreateGadgets < ActiveRecord::Migration
def change
create_table "gadgets" do |t|
t.string "info"
end
end
end
class Gadget < ActiveRecord::Base
serialize :info, HashieMashSerializedAsJson
# This allows the field to be set as a Hash or anything compatible with it.
def info=(new_value)
self[:info] = HashieMashSerializedAsJson.new new_value
end
end
# An ActiveRecord field serializer, presenting as a Mashie::Hash and stored as a JSON string in postgres.
# Of course, you need to include the hashie gem: https://github.com/intridea/hashie
class HashieMashSerializedAsJson < Hashie::Mash
def self.dump(obj)
ActiveSupport::JSON.encode(obj.to_h)
end
def self.load(json)
new(json ? ActiveSupport::JSON.decode(json) : {})
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment