Last active
July 28, 2017 06:07
-
-
Save herenow/093e630987f0df1ae86b9de4d22c07a1 to your computer and use it in GitHub Desktop.
Pass Virtus/Attribute classes to Rails' ActiveRecord serialize (as json)
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
# lib/json_serializer.rb | |
class JsonSerializer | |
# Dumps objects to json. | |
# Loads json into specified class. | |
# | |
# e.g: | |
# | |
# class User | |
# serialize :data, JsonSerializer.new(DataObject) | |
# end | |
# | |
# Will serialize any instance of DataObject into a json string. | |
# Will unserialize any json string into an DataObject instance. | |
# Params: | |
# +klass+:: Class that parsed attributes will be initialized into | |
def initialize(klass) | |
@klass = klass | |
end | |
def dump(object) | |
object.as_json | |
end | |
def load(hash) | |
if hash.is_a? String | |
hash = JSON.parse(hash) | |
end | |
@klass.new(hash) | |
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
# app/models/data_object.rb | |
class DataObject | |
include Virtus.model | |
attribute :moves, String | |
attribute :like, String | |
attribute :jagger, String | |
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
# app/models/user.rb | |
require './lib/json_serializer' | |
class User | |
serialize :data, JsonSerializer.new(DataObject) | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
If you have a json/jsonb
data
column, you might expect the following to dump yourDataObject
instanceas_json
to the database.But this will actually serialize your
DataObject
throughYAML
, see.Not sure if this is something that Rails should check for: by default, if it's a
json/jsonb
column, when dumping call the methodas_json
, when loading initialize the json into the provided class, instead of usingYAML
.