Sha256: 2af2cbc7662e40609a81adb4bda5279ef9ff68fe926ddb59f97c4702dde6c7af

Contents?: true

Size: 1.18 KB

Versions: 1

Compression:

Stored size: 1.18 KB

Contents

module Serialism

  # Base class for concrete serializers to inherit from.
  #
  # Example:
  #
  #   class Foo
  #     attr_accessor :id
  #   end
  #
  #   class FooSerializer < Serialism::Serializer
  #     attributes :id, :computed
  #
  #     def computed
  #       "computed - #{object.id}"
  #     end
  #   end
  #
  #   item = Foo.new
  #   item.id = 12
  #
  #   serializer = FooSerializer.new(item)
  #   serializer.render
  #   # => {id: 12, computed: "computed - 12"}
  class Serializer

    attr_reader :object

    @attributes = []
    def self.attributes(*attrs)
      if attrs.size > 0
        @attributes = attrs
      end
      @attributes
    end

    def initialize(object)
      @object = object
    end

    # Transform `object` using rules defined by the serializer.
    #
    # @return [Hash] Keys are defined by the classes `attributes`.
    def render
      self.class.attributes.inject({}) do |memo,attr|
        if respond_to?(attr)
          memo[attr] = self.send(attr)
        elsif object.respond_to?(attr)
          memo[attr] = object.send(attr)
        else
          raise ArgumentError, "Unknown attribute :#{attr}"
        end
        memo
      end
    end

  end

end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
serialism-0.0.1 lib/serialism/serializer.rb