Sha256: a817c9f0386a7a7f6a3c4afbb7786e0b7654bb1aa1182fae77d5e47c0d9b806f

Contents?: true

Size: 938 Bytes

Versions: 3

Compression:

Stored size: 938 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 = -> { @_resource.to_json }
        case Alba.backend
        when :oj
          begin
            require 'oj'
            -> { Oj.dump(@_resource) }
          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

3 entries across 3 versions & 1 rubygems

Version Path
alba-0.3.0 lib/alba/serializer.rb
alba-0.2.0 lib/alba/serializer.rb
alba-0.1.0 lib/alba/serializer.rb