module RiceBubble class Serializer attr_reader :object def initialize(object = nil) @object = object end def call(object_to_serialize = nil, path: nil) if object_to_serialize self.class.new(object_to_serialize).call(path:) elsif object self.class.attributes.map do |name, attr| attr.call(fetch(name), path: "#{path || self.class.name}.#{name}") end else raise ArgumentError, 'no object to serialize' end end def fetch(name) if respond_to?(name) public_send(name) else self.class.attributes[name].fetch(object, name) end end def valid?(object) self.class.attributes.all? do |name, attr| attr.valid?(attr.fetch(object, name)) end end class << self def call(object = nil, ...) new(object).call(...) end def attributes(attrs = nil, &) @attributes ||= if superclass == Object Attributes.new else superclass.attributes.dup end @attributes.instance_eval(&) if block_given? attrs&.each_pair { |name, attr| @attributes[name] = attr } @attributes end def respond_to_missing?(name, include_private = false) !Attributes[name].nil? || super end def method_missing(name, *args, **kwargs, &) Attributes[name]&.new(*args, **kwargs, &) || super end def as(...) serialized(...) end alias of as end end end