DEV Community

Piotr Romańczuk
Piotr Romańczuk

Posted on • Updated on

Transparently serialize and deserialize ValueObjects to JSON

This is the way I choose when I want to serialize and deserialize ValueObjects transparently to JSON in Rails app

Put serialization methods into module

module ValueObjectJsonSerialization
  def to_json(*args)
    #override AtiveSupport to_json extensions if active
    args = JSON::SAFE_STATE_PROTOTYPE.dup if args == []
    {
      :json_class => self.class.to_s,
    }.merge(as_json).to_json(*args)
  end

  def as_json(_=nil)
    # unused argument to satisfy ActiveSupport as_json signature
    { :json_class => self.class.to_s }.merge(_as_json)
  end
end

Enter fullscreen mode Exit fullscreen mode

Use them in your ValueObject class and make it transparently serializable

class PublicationDate
  include ValueObjectJsonSerialization
  def initialize(y, m=nil, d=nil)
    @y, @m, @d = y, m, d 
  end

  def self.