Sha256: fb8c9483d087778b3f1d5fb8e399d8d7b8796544d62d23b49cf46339d531cb9e

Contents?: true

Size: 1006 Bytes

Versions: 2

Compression:

Stored size: 1006 Bytes

Contents

module Alba
  # This module represents how a resource should be serialized.
  #
  module Serializer
    def self.included(base)
      base.include InstanceMethods
      base.extend ClassMethods
    end

    # Instance methods
    module InstanceMethods
      def initialize(resource)
        @_resource = resource
        @_opts = self.class._opts || {}
        key = @_opts[:key]
        @_resource = {key.to_sym => @_resource} if key
      end

      def serialize
        fallback = lambda do
          require 'json'
          JSON.dump(@_resource)
        end
        case Alba.backend
        when :oj
          begin
            require 'oj'
            -> { Oj.dump(@_resource, mode: :strict) }
          rescue LoadError
            fallback
          end
        else
          fallback
        end.call
      end
    end

    # Class methods
    module ClassMethods
      attr_reader :_opts

      def set(key: false)
        @_opts ||= {}
        @_opts[:key] = key
      end
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
alba-0.5.0 lib/alba/serializer.rb
alba-0.4.0 lib/alba/serializer.rb