lib/alba.rb in alba-2.2.0 vs lib/alba.rb in alba-2.3.0

- old
+ new

@@ -42,17 +42,27 @@ # @param object [Object] the object to be serialized # @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, root_key: nil, &block) - klass = block ? resource_class(&block) : infer_resource_class(object.class.name) - - resource = klass.new(object) + def serialize(object = nil, root_key: nil, &block) + resource = resource_with(object, &block) resource.serialize(root_key: root_key) end + # Hashify the object with inline definitions + # + # @param object [Object] the object to be serialized + # @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 hashify(object = nil, root_key: nil, &block) + resource = resource_with(object, &block) + resource.as_json(root_key: root_key) + end + # Enable inference for key and resource name # # @param with [Symbol, Class, Module] inflector # When it's a Symbol, it sets inflector with given name # When it's a Class or a Module, it sets given object to inflector @@ -105,30 +115,58 @@ const_parent = nesting.nil? ? Object : Object.const_get(nesting) const_parent.const_get("#{inflector.classify(name)}Resource") end + # Configure Alba to symbolize keys + def symbolize_keys! + @symbolize_keys = true + end + + # Configure Alba to stringify (not symbolize) keys + def stringify_keys! + @symbolize_keys = false + end + + # Regularize key to be either Symbol or String depending on @symbolize_keys + # Returns nil if key is nil + # + # @param key [String, Symbol, nil] + # @return [Symbol, String, nil] + def regularize_key(key) + return if key.nil? + + @symbolize_keys ? key.to_sym : key.to_s + end + # Reset config variables # Useful for test cleanup def reset! @encoder = default_encoder + @symbolize_keys = false @_on_error = :raise @_on_nil = nil end private + # This method could be part of public API, but for now it's private + def resource_with(object, &block) + klass = block ? resource_class(&block) : infer_resource_class(object.class.name) + + klass.new(object) + end + def inflector_from(name_or_module) case name_or_module when nil then nil when :default, :active_support require_relative 'alba/default_inflector' Alba::DefaultInflector when :dry require 'dry/inflector' Dry::Inflector.new - else - validate_inflector(name_or_module) + else validate_inflector(name_or_module) end end def set_encoder_from_backend @encoder = case @backend