Class: ActsAsHashable::TypeFactory
- Inherits:
-
Object
- Object
- ActsAsHashable::TypeFactory
- Defined in:
- lib/acts_as_hashable/type_factory.rb
Overview
A TypeFactory object understands how to build objects using a special designated ‘type’ key.
Constant Summary collapse
- DEFAULT_TYPE_KEY =
:type
Instance Attribute Summary collapse
-
#registry ⇒ Object
readonly
Returns the value of attribute registry.
-
#type_key ⇒ Object
readonly
Returns the value of attribute type_key.
Instance Method Summary collapse
- #array(objects = []) ⇒ Object
-
#initialize(registry = {}, type_key = DEFAULT_TYPE_KEY) ⇒ TypeFactory
constructor
A new instance of TypeFactory.
- #make(config = {}) ⇒ Object
Constructor Details
#initialize(registry = {}, type_key = DEFAULT_TYPE_KEY) ⇒ TypeFactory
Returns a new instance of TypeFactory.
21 22 23 24 25 26 27 |
# 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 |
Instance Attribute Details
#registry ⇒ Object (readonly)
Returns the value of attribute registry.
19 20 21 |
# File 'lib/acts_as_hashable/type_factory.rb', line 19 def registry @registry end |
#type_key ⇒ Object (readonly)
Returns the value of attribute type_key.
19 20 21 |
# File 'lib/acts_as_hashable/type_factory.rb', line 19 def type_key @type_key end |
Instance Method Details
#array(objects = []) ⇒ Object
29 30 31 32 33 34 35 |
# 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 = {}) ⇒ Object
37 38 39 40 41 42 43 44 45 46 47 48 49 50 |
# 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 |