class ActsAsHashable::TypeFactory
A TypeFactory
object understands how to build objects using a special designated 'type' key.
Constants
- DEFAULT_TYPE_KEY
Attributes
constant_resolver[R]
registry[R]
type_key[R]
Public Class Methods
new(registry = {}, type_key = DEFAULT_TYPE_KEY)
click to toggle source
# File lib/acts_as_hashable/type_factory.rb, line 21 def initialize(registry = {}, type_key = DEFAULT_TYPE_KEY) @constant_resolver = ConstantResolver.new @registry = registry.symbolize_keys @type_key = type_key.to_s.to_sym freeze end
Public Instance Methods
array(objects = [])
click to toggle source
# File lib/acts_as_hashable/type_factory.rb, line 29 def array(objects = []) objects = objects.is_a?(Hash) ? [objects] : Array(objects) objects.map do |object| object.is_a?(Hash) ? make(object) : object end end
make(config = {})
click to toggle source
# File lib/acts_as_hashable/type_factory.rb, line 37 def make(config = {}) config = (config || {}).symbolize_keys type = config[type_key].to_s.to_sym object_class = resolve_object_class(type) 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
Private Instance Methods
resolve_object_class(type)
click to toggle source
# File lib/acts_as_hashable/type_factory.rb, line 56 def resolve_object_class(type) object_class = registry[type] raise ArgumentError, "cannot find registration for: '#{type}'" unless object_class return object_class unless object_class.is_a?(String) constant_resolver.constantize(object_class) end