'How to override the type of existing attributes in ruby sequel?

In ActiveRecord, overriding the type of existing model attribute is easy:

class CustomAddress < ActiveRecord::Type::String
  def deserialize(value)
    super(value.to_s + " deserialized")
  end

  def serialize(value)
    super(value.to_s + " serialized")
  end
end

User.attribute(:address, CustomAddress.new)
User.first.address # "deserialized"
User.first.update(address: "Street A, District B")
User.first.address # prints "Street A, District B serialized deserialized"
# note that in the database, User.first.address is "Street A, District B serialized"

I can't seem to find an alternative approach for the Sequel library, and is wondering if you can achieve the same behavior in Sequel as you do with ActiveRecord? I've read https://www.rubydoc.info/gems/sequel/4.35.0/Sequel/Model/ClassMethods but don't see a similar method to ActiveRecord#attribute, and Sequel doesn't have callbacks/hooks when invoking getter/setter method of model attribute either...

I can override the getter/setter methods of an attribute using define_method - but I want to avoid it because I would like to keep the existing override methods intact.

Refs:

https://api.rubyonrails.org/classes/ActiveRecord/Attributes/ClassMethods.html#method-i-attribute https://www.rubydoc.info/gems/activerecord/4.2.7/ActiveRecord/Type/String



Solution 1:[1]

Answer from @engineersmnky, using Sequel::Plugins::Serialization:

require 'sequel/plugins/serialization'

class User < Sequel::Model(DB[:users])
  plugin :serialization

  serialize_attributes [->(value) { "#{value} serialized" }, ->(value) { "#{value} deserialized" }], :address
end

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Huy Vo