lib/alba.rb in alba-1.4.0 vs lib/alba.rb in alba-1.5.0
- old
+ new
@@ -1,8 +1,9 @@
require 'json'
require_relative 'alba/version'
require_relative 'alba/resource'
+require_relative 'alba/deprecation'
# Core module
module Alba
# Base class for Errors
class Error < StandardError; end
@@ -12,11 +13,11 @@
# Error class for type which is not supported
class UnsupportedType < Error; end
class << self
- attr_reader :backend, :encoder, :inferring, :_on_error, :transforming_root_key
+ attr_reader :backend, :encoder, :inferring, :_on_error, :_on_nil, :transforming_root_key
# Accessor for inflector, a module responsible for incflecting strings
attr_accessor :inflector
# Set the backend, which actually serializes object into JSON
@@ -49,11 +50,11 @@
# @param root_key [Symbol, nil, true]
# @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, key: nil, root_key: nil, &block)
- warn '`key` option to `serialize` method is deprecated, use `root_key` instead.' if key
+ Alba::Deprecation.warn '`key` option to `serialize` method is deprecated, use `root_key` instead.' if key
klass = block ? resource_class(&block) : infer_resource_class(object.class.name)
resource = klass.new(object)
resource.serialize(root_key: root_key || key)
end
@@ -85,10 +86,18 @@
raise ArgumentError, 'You must specify error handler with either Symbol or block' unless handler || block
@_on_error = handler || block
end
+ # Set nil handler
+ #
+ # @param block [Block]
+ # @return [void]
+ def on_nil(&block)
+ @_on_nil = block
+ end
+
# Enable root key transformation
def enable_root_key_transformation!
@transforming_root_key = true
end
@@ -113,10 +122,19 @@
enable_inference!
const_parent = nesting.nil? ? Object : Object.const_get(nesting)
const_parent.const_get("#{ActiveSupport::Inflector.classify(name)}Resource")
end
+ # Reset config variables
+ # Useful for test cleanup
+ def reset!
+ @encoder = default_encoder
+ @_on_error = :raise
+ @_on_nil = nil
+ @transforming_root_key = false # TODO: This will be true since 2.0
+ end
+
private
def set_encoder_from_backend
@encoder = case @backend
when :oj, :oj_strict then try_oj
@@ -149,9 +167,7 @@
JSON.dump(hash)
end
end
end
- @encoder = default_encoder
- @_on_error = :raise
- @transforming_root_key = false # TODO: This will be true since 2.0
+ reset!
end