dry-struct and serializer

Hi,

I have a model User with columns “name, email, phone, and hobbies” - hobbies - is hstore - type

before dry I used Virtus and can serialize this field with virtus model.

now I’m trying to change and have an error

SystemStackError: stack level too deep

model

serialize :hobbies, UserHobby

dry

class UserHobby < Dry::Struct
  module Types
    include Dry::Types(default: :nominal)
  end

  attribute? :football, Types::Bool.default(true)
  attribute? :basketball, Types::Bool.default(true)
  attribute? :tenis, Types::Bool.default(false)

  def self.dump(user_hobby)
    # binding.pry
    user_hobby.to_hash
  end

  def self.load(user_hobby)
    new(user_hobby)
  end
end

how can I fix that?

It’s because load is already part of the Dry::Struct interface, which gets called during initialization.

Try something like this:

class StructCoder
  attr_reader :struct

  def initialize(struct)
    @struct = struct
  end

  def dump(s)
    s.to_hash
  end

  def load(h)
    struct.new(h)
  end
end

class UserHobby < Dry::Struct
  transform_keys(&:to_sym)

  module Types
    include Dry::Types(default: :nominal)
  end

  attribute? :football, Types::Params::Bool.default(true)
  attribute? :basketball, Types::Params::Bool.default(true)
  attribute? :tennis, Types::Params::Bool.default(false)
end

class User < ActiveRecord::Base
  serialize :hobbies, StructCoder.new(UserHobby)
end

thx you, looks like working!