I’ll continue this thread because I’m trying to do the same thing.
Say I have a user model with a hstore
column:
class User < ApplicationRecord
serialize :meta, Options
end
With a Meta
virtus class that looks like:
class Meta
include Virtus.model
attribute :badge_number, Integer
attribute :reminders_enabled, Boolean, default: false
attribute :nickname, String
def self.dump(meta)
meta.to_hash
end
def self.load(meta
new(meta)
end
end
If the hstore content of meta
is "nickname"=>"awesome", "badge_number"=>"12", "reminders_enabled"=>"true"
, virtus will properly coerce the values in the Preferences::User class and I can do things such as user.meta.badge_number = 1; user.save
and Rails/virtus does all of the right things and updates the backing hstore column.
How do I implement such functionality with dry types?
I’ve tried
module Types
include Dry::Types.module
end
class Meta < Dry::Struct
constructor_type :schema
attribute :badge_number, Types::Int
attribute :reminders_enabled, Types::Bool
attribute :nickname, String
def self.dump(meta)
meta.to_hash
end
def self.load(meta)
new(meta)
end
end
but all of the attributes in meta
are then nil.
If I try with the permissive
constructor type, I get Dry::Struct::Error ([Meta.new] :badge_number is missing in Hash input)
.
I use this pattern of a hstore
meta or options or some column, serialized with Virtus all over my app, it’s been super useful. I feel like I’m missing something obvious here, so would appreciate any help you all can offer.
Thanks!