Sha256: e2ad76fdc159de1329222a8838b666f586d6e2f4931c13f157b90e81e618fa32

Contents?: true

Size: 1.8 KB

Versions: 1

Compression:

Stored size: 1.8 KB

Contents

module Shamu
  module JsonApi

    # Used by a {Serilaizer} to write fields and relationships
    class BaseBuilder

      # ============================================================================
      # @!group Attributes
      #

      # @!attribute
      # @return [Context] the JSON serialization context.
        attr_reader :context

      #
      # @!endgroup Attributes


      # @param [Context] context the current serialization context.
      def initialize( context )
        @context = context
        @output = {}
      end

      # Write a resource linkage info.
      #
      # @param [String] type of the resource.
      # @param [Object] id of the resource.
      # @return [void]
      def identifier( type, id = nil )
        output[:type] = type.to_s
        output[:id]   = id.to_s
      end

      # Write a link  to another resource.
      #
      # @param [String,Symbol] name of the link.
      # @param [String] url
      # @param [Hash] meta optional additional meta information.
      # @return [void]
      def link( name, url, meta: nil )
        links = ( output[:links] ||= {} )

        if meta # rubocop:disable Style/ConditionalAssignment
          links[ name.to_sym ] = { href: url, meta: meta }
        else
          links[ name.to_sym ] = url
        end
      end

      # Add a meta field.
      # @param [String,Symbol] name of the meta field.
      # @param [Object] vlaue that can be converted to a JSON primitive type.
      # @return [void]
      def meta( name, value )
        meta = ( output[:meta] ||= {} )
        meta[ name.to_sym ] = value
      end

      # @return [Hash] the results output as JSON safe hash.
      def compile
        fail JsonApi::IncompleteResourceError unless output[:type]
        output
      end

      private

        attr_reader :output

    end
  end
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
shamu-0.0.4 lib/shamu/json_api/base_builder.rb