Sha256: 00029342f75d4c097d59371b22ef0ea90c33f979beedc00eaeaa3d4e5c7fb102

Contents?: true

Size: 904 Bytes

Versions: 1

Compression:

Stored size: 904 Bytes

Contents

# frozen_string_literal: true

require "json"

module Transmutation
  class Serializer # rubocop:disable Style/Documentation
    def initialize(object)
      @object = object
    end

    def to_json(options = {})
      as_json(options).to_json
    end

    def as_json(_options = {})
      _attributes.each_with_object({}) do |(attr_name, attr_options), hash|
        hash[attr_name.to_s] = attr_options[:block] ? instance_exec(&attr_options[:block]) : object.send(attr_name)
      end
    end

    def self.attribute(attr_name, &block)
      _attributes[attr_name] = { block: block }
    end

    def self.attributes(*attr_name)
      attr_name.each do |name|
        attribute(name)
      end
    end

    def self._attributes
      @@attributes ||= {} # rubocop:disable Style/ClassVars
    end

    def _attributes
      self.class._attributes
    end

    private

    attr_reader :object
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
transmutation-0.1.0 lib/transmutation/serializer.rb