lib/alba.rb in alba-0.8.0 vs lib/alba.rb in alba-0.9.0
- old
+ new
@@ -7,15 +7,16 @@
# Core module
module Alba
class Error < StandardError; end
class << self
- attr_reader :backend
+ 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
@@ -25,10 +26,42 @@
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