Sha256: 0bff6611b4e354c2492a55d848ad718f14527382f004ee2269bf968afc344070

Contents?: true

Size: 1.86 KB

Versions: 2

Compression:

Stored size: 1.86 KB

Contents

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)
        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

    def validate!(object, path: '', **)
      path = self.class.name if path.empty?

      self.class.attributes.each do |name, attr|
        value = attr.fetch(object, name)
        attr.validate!(
          value,
          coerced: attr.coerce(value),
          path: "#{path}.#{name}"
        )
      end
    end

    def coerce(object)
      object
    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

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
rice_bubble-0.1.2 lib/rice_bubble/serializer.rb
rice_bubble-0.1.1 lib/rice_bubble/serializer.rb