Sha256: ac9c3151c3a2a18080de48e11a56aa992a8317e4552c32952d6137c7a191b90c

Contents?: true

Size: 1.59 KB

Versions: 3

Compression:

Stored size: 1.59 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
  # This class serves as a singleton that can make mapped acts_as_hashable components.
  # It is important to note that these components *must* be acts_as_hashable objects.
  # In order to use you just have to subclass this class and implement
  # a method called 'registry', such as:
  #   def registry
  #     {
  #       'Table': Table,
  #       'Text': Text
  #     }
  #   end
  # You can also use the 'register' DSL:
  #   register 'some_class_name', SomeClassName
  #   register 'some_class_name', '', SomeClassName
  # or:
  #   register 'some_class_name', ->(_key) { SomeClassName }
  module Factory
    extend Forwardable

    def_delegators :factory, :array, :make

    def register(*args)
      raise ArgumentError, "missing at least one key and value: #{args}" if args.length < 2

      value = args.last

      args[0..-2].each do |key|
        registry[key] = value
      end
    end

    def registry # :nodoc:
      @registry ||= {}
    end

    def materialize_registry # :nodoc:
      @registry.map do |k, v|
        value = v.is_a?(Proc) ? v.call(k) : v
        [k, value]
      end.to_h
    end

    def type_key(key) # :nodoc:
      @typed_with = key
    end

    def typed_with # :nodoc:
      @typed_with || TypeFactory::DEFAULT_TYPE_KEY
    end

    private

    def factory
      @factory ||= TypeFactory.new(materialize_registry, typed_with)
    end
  end
end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
acts_as_hashable-1.3.2 lib/acts_as_hashable/factory.rb
acts_as_hashable-1.3.1 lib/acts_as_hashable/factory.rb
acts_as_hashable-1.3.0 lib/acts_as_hashable/factory.rb