Created
February 1, 2016 04:20
-
-
Save RobinDaugherty/bafe6716b984f8bcc87e to your computer and use it in GitHub Desktop.
ActiveRecord attribute serializer Hashie::Mash stored as a JSON string in Postgres
This file contains 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.string "info" | |
end | |
end | |
end |
This file contains 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, 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 |
This file contains 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 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