Sha256: 504b345f903bdee38b95e4597dcfeb627082b8bc4cd8312d26f598efe50ec730

Contents?: true

Size: 1.05 KB

Versions: 1

Compression:

Stored size: 1.05 KB

Contents

# frozen_string_literal: true

# class UserSerializer < BasicSerializer
#   attribute :id, :integer
#   attribute :name, :string
#   attribute :email, :string
# end

require "oj"

class BasicSerializer
  VERSION = "0.1.0"

  class << self
    def attributes
      @attributes ||= {}
    end

    def attribute(name, type)
      attributes[name] = type

      return if method_defined?(name)

      define_method(name) { object[name] }
    end
  end

  attr_reader :object

  def initialize(object)
    @object = case object
              when Hash
                object.transform_keys(&:to_sym)
              when ->(obj) { obj.respond_to?(:attributes) }
                object.attributes
              when ->(obj) { obj.respond_to?(:values) }
                object.values.transform_keys(&:to_sym)
              else
                object
              end
  end

  def as_json
    self.class.attributes.keys.each_with_object({}) do |attr_name, hash|
      hash[attr_name.to_s] = send(attr_name)
    end
  end

  def to_json(*_args)
    Oj.dump(as_json, indent: 2)
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
basic_serializer-0.1.0 lib/basic_serializer.rb