lib/alba.rb in alba-0.13.1 vs lib/alba.rb in alba-1.0.0
- old
+ new
@@ -1,7 +1,6 @@
require_relative 'alba/version'
-require_relative 'alba/serializer'
require_relative 'alba/resource'
# Core module
module Alba
# Base class for Errors
@@ -9,12 +8,11 @@
# Error class for backend which is not supported
class UnsupportedBackend < Error; end
class << self
- attr_reader :backend, :encoder
- attr_accessor :default_serializer
+ attr_reader :backend, :encoder, :inferring, :_on_error
# Set the backend, which actually serializes object into JSON
#
# @param backend [#to_sym, nil] the name of the backend
# Possible values are `oj`, `active_support`, `default`, `json` and nil
@@ -26,23 +24,49 @@
end
# Serialize the object with inline definitions
#
# @param object [Object] the object to be serialized
- # @param with [nil, Proc, Alba::Serializer] selializer
+ # @param key [Symbol]
# @param block [Block] resource block
# @return [String] serialized JSON string
# @raise [ArgumentError] if block is absent or `with` argument's type is wrong
- def serialize(object, with: nil, &block)
+ def serialize(object, key: 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)
+ resource.serialize(key: key)
end
+ # Enable inference for key and resource name
+ def enable_inference!
+ begin
+ require 'active_support/inflector'
+ rescue LoadError
+ raise ::Alba::Error, 'To enable inference, please install `ActiveSupport` gem.'
+ end
+ @inferring = true
+ end
+
+ # Disable inference for key and resource name
+ def disable_inference!
+ @inferring = false
+ end
+
+ # Set error handler
+ #
+ # @param [Symbol] handler
+ # @param [Block]
+ def on_error(handler = nil, &block)
+ raise ArgumentError, 'You cannot specify error handler with both Symbol and block' if handler && block
+ raise ArgumentError, 'You must specify error handler with either Symbol or block' unless handler || block
+
+ p block if block
+ @_on_error = handler || block
+ end
+
private
def set_encoder
@encoder = case @backend
when :oj
@@ -84,6 +108,7 @@
end
end
end
@encoder = default_encoder
+ @_on_error = :raise
end