Sha256: 9ef4cee846b45376723d7773e02e2441cb2d427b8fc6b5411b3376445ec1f251

Contents?: true

Size: 1.65 KB

Versions: 1

Compression:

Stored size: 1.65 KB

Contents

require 'alba/version'
require 'alba/serializers/default_serializer'
require 'alba/serializer'
require 'alba/resource'
require 'alba/resources/default_resource'

# Core module
module Alba
  class Error < StandardError; end

  class << self
    attr_reader :backend, :encoder
    attr_accessor :default_serializer

    def backend=(backend)
      @backend = backend&.to_sym
      set_encoder
    end

    def serialize(object, with: nil, &block)
      raise ArgumentError, 'Block required' unless block

      resource_class.class_eval(&block)
      resource = resource_class.new(object)
      with ||= @default_serializer
      resource.serialize(with: with)
    end

    private

    def set_encoder
      @encoder = case @backend
                 when :oj
                   begin
                     require 'oj'
                     ->(hash) { Oj.dump(hash, mode: :strict) }
                   rescue LoadError
                     default_encoder
                   end
                 when :active_support
                   begin
                     require 'active_support/json'
                     ->(hash) { ActiveSupport::JSON.encode(hash) }
                   rescue LoadError
                     default_encoder
                   end
                 when nil, :default, :json
                   default_encoder
                 else
                   raise Alba::Error, "Unsupported backend, #{backend}"
                 end
    end

    def default_encoder
      lambda do |hash|
        require 'json'
        JSON.dump(hash)
      end
    end

    def resource_class
      ::Alba::Resources::DefaultResource.clone
    end
  end

  @encoder = default_encoder
end

Version data entries

1 entries across 1 versions & 1 rubygems

Version Path
alba-0.9.0 lib/alba.rb