lib/alba.rb in alba-2.4.3 vs lib/alba.rb in alba-3.0.0
- old
+ new
@@ -114,11 +114,11 @@
raise Alba::Error, 'Inference is disabled so Alba cannot infer resource name. Set inflector before use.' unless Alba.inflector
const_parent = nesting.nil? ? Object : Object.const_get(nesting)
begin
const_parent.const_get("#{inflector.classify(name)}Resource")
- rescue # Retry for serializer
+ rescue NameError # Retry for serializer
const_parent.const_get("#{inflector.classify(name)}Serializer")
end
end
# Configure Alba to symbolize keys
@@ -140,17 +140,36 @@
return if key.nil?
@symbolize_keys ? key.to_sym : key.to_s
end
+ # Register types, used for both builtin and custom types
+ #
+ # @see Alba::Type
+ # @return [void]
+ def register_type(name, check: false, converter: nil, auto_convert: false)
+ @types[name] = Type.new(name, check: check, converter: converter, auto_convert: auto_convert)
+ end
+
+ # Find type by name
+ #
+ # @return [Alba::Type]
+ def find_type(name)
+ @types.fetch(name) do
+ raise(Alba::UnsupportedType, "Unknown type: #{name}")
+ end
+ end
+
# Reset config variables
# Useful for test cleanup
def reset!
@encoder = default_encoder
@symbolize_keys = false
@_on_error = :raise
@_on_nil = nil
+ @types = {}
+ register_default_types
end
private
# This method could be part of public API, but for now it's private
@@ -173,21 +192,21 @@
end
end
def set_encoder_from_backend
@encoder = case @backend
- when :oj, :oj_strict then try_oj
+ when :oj, :oj_strict then try_oj(mode: :strict)
when :oj_rails then try_oj(mode: :rails)
when :oj_default then try_oj(mode: :default)
when :active_support then try_active_support
when nil, :default, :json then default_encoder
else
raise Alba::UnsupportedBackend, "Unsupported backend, #{backend}"
end
end
- def try_oj(mode: :strict)
+ def try_oj(mode:)
require 'oj'
case mode
when :default
->(hash) { Oj.dump(hash) }
else
@@ -216,9 +235,17 @@
unless %i[camelize camelize_lower dasherize classify].all? { |m| inflector.respond_to?(m) }
raise Alba::Error, "Given inflector, #{inflector.inspect} is not valid. It must implement `camelize`, `camelize_lower`, `dasherize` and `classify`."
end
inflector
+ end
+
+ def register_default_types # rubocop:disable Metrics/AbcSize
+ register_type(:String, check: ->(obj) { obj.is_a?(String) }, converter: ->(obj) { obj.to_s })
+ register_type(String, check: ->(obj) { obj.is_a?(String) }, converter: ->(obj) { obj.to_s })
+ register_type(:Integer, check: ->(obj) { obj.is_a?(Integer) }, converter: ->(obj) { Integer(obj) })
+ register_type(Integer, check: ->(obj) { obj.is_a?(Integer) }, converter: ->(obj) { Integer(obj) })
+ register_type(:Boolean, check: ->(obj) { [true, false].include?(obj) }, converter: ->(obj) { !!obj })
end
end
reset!
end