lib/alba.rb in alba-3.2.0 vs lib/alba.rb in alba-3.3.0
- old
+ new
@@ -1,5 +1,7 @@
+# frozen_string_literal: true
+
require 'json'
require_relative 'alba/version'
require_relative 'alba/errors'
require_relative 'alba/resource'
require_relative 'alba/deprecation'
@@ -140,10 +142,30 @@
return if key.nil?
@symbolize_keys ? key.to_sym : key.to_s
end
+ # Transform a key with given transform_type
+ #
+ # @param key [String] a target key
+ # @param transform_type [Symbol] a transform type, either one of `camel`, `lower_camel`, `dash` or `snake`
+ # @return [String]
+ def transform_key(key, transform_type:)
+ raise Alba::Error, 'Inflector is nil. You must set inflector before transforming keys.' unless inflector
+
+ key = key.to_s
+
+ k = case transform_type
+ when :camel then inflector.camelize(key)
+ when :lower_camel then inflector.camelize_lower(key)
+ when :dash then inflector.dasherize(key)
+ when :snake then inflector.underscore(key)
+ else raise Alba::Error, "Unknown transform type: #{transform_type}"
+ end
+ regularize_key(k)
+ 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)
@@ -237,17 +259,20 @@
end
inflector
end
- def register_default_types
+ def register_default_types # rubocop:disable Mertics/AbcSize
[String, :String].each do |t|
register_type(t, check: ->(obj) { obj.is_a?(String) }, converter: lambda(&:to_s))
end
[Integer, :Integer].each do |t|
register_type(t, check: ->(obj) { obj.is_a?(Integer) }, converter: ->(obj) { Integer(obj) })
end
register_type(:Boolean, check: ->(obj) { [true, false].include?(obj) }, converter: ->(obj) { !!obj })
+ [String, Integer].each do |t|
+ register_type(:"ArrayOf#{t}", check: ->(d) { d.is_a?(Array) && d.all? { _1.is_a?(t) } })
+ end
end
end
reset!
end