Sha256: f8eafca3b2adc3c78efeb98e74e6ec3a053219806dbfd5d72c5a746075af079c
Contents?: true
Size: 1.49 KB
Versions: 2
Compression:
Stored size: 1.49 KB
Contents
# frozen_string_literal: true # # Copyright (c) 2019-present, Blue Marble Payroll, LLC # # This source code is licensed under the MIT license found in the # LICENSE file in the root directory of this source tree. # module ActsAsHashable # A TypeFactory object understands how to build objects using a special designated 'type' key. class TypeFactory using HashRefinements DEFAULT_TYPE_KEY = :type attr_reader :registry, :type_key def initialize(registry = {}, type_key = DEFAULT_TYPE_KEY) @registry = registry.symbolize_keys @type_key = type_key.to_s.to_sym freeze end def array(objects = []) objects = objects.is_a?(Hash) ? [objects] : Array(objects) objects.map do |object| object.is_a?(Hash) ? make(object) : object end end def make(config = {}) config = (config || {}).symbolize_keys type = config[type_key].to_s.to_sym object_class = registry[type] raise ArgumentError, "cannot find registration for: '#{type}'" unless object_class config_without_type = config.reject { |k| k == type_key } # We want to defer to the classes proper maker if it exists. # Technically, this factory should only make classes that include Hashable, but just to be # sure we do not break any existing compatibility, lets make it work for both. method_name = object_class.respond_to?(:make) ? :make : :new object_class.send(method_name, config_without_type) end end end
Version data entries
2 entries across 2 versions & 1 rubygems
Version | Path |
---|---|
acts_as_hashable-1.2.0 | lib/acts_as_hashable/type_factory.rb |
acts_as_hashable-1.2.0.pre.alpha.1 | lib/acts_as_hashable/type_factory.rb |