Skip to content

Instantly share code, notes, and snippets.

@herenow
Last active July 28, 2017 06:07
Show Gist options
  • Save herenow/093e630987f0df1ae86b9de4d22c07a1 to your computer and use it in GitHub Desktop.
Save herenow/093e630987f0df1ae86b9de4d22c07a1 to your computer and use it in GitHub Desktop.
Pass Virtus/Attribute classes to Rails' ActiveRecord serialize (as json)
# 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
# app/models/data_object.rb
class DataObject
include Virtus.model
attribute :moves, String
attribute :like, String
attribute :jagger, String
end
# app/models/user.rb
require './lib/json_serializer'
class User
serialize :data, JsonSerializer.new(DataObject)
end
@herenow
Copy link
Author

herenow commented Jul 27, 2017

If you have a json/jsonb data column, you might expect the following to dump your DataObject instance as_json to the database.

serialize :data, DataObject

But this will actually serialize your DataObject through YAML, see.

--- !ruby/object:DataObject\n...

Not sure if this is something that Rails should check for: by default, if it's a json/jsonb column, when dumping call the method as_json, when loading initialize the json into the provided class, instead of using YAML.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment