Module: ObjectForge::Molds
- Defined in:
- lib/object_forge/molds.rb,
lib/object_forge/molds/hash_mold.rb,
lib/object_forge/molds/array_mold.rb,
lib/object_forge/molds/struct_mold.rb,
lib/object_forge/molds/wrapped_mold.rb,
lib/object_forge/molds/keywords_mold.rb,
lib/object_forge/molds/single_argument_mold.rb
Overview
This module provides a collection of predefined molds to be used in common cases.
Mold is an object that knows how to take a hash of attributes and create an object from them. Molds are callable objects responsible for actually building objects produced by factories (or doing other, interesting things with them (truly, only the code review is the limit!)). They are supposed to be immutable, shareable, and persistent: initialize once, use for the whole runtime.
A simple mold can easily be just a Proc. All molds must have the following #call signature: call(forge_target:, attributes:, **). The extra keywords are ignored for possibility of future extensions.
Defined Under Namespace
Classes: ArrayMold, HashMold, KeywordsMold, SingleArgumentMold, StructMold, WrappedMold
Class Method Summary collapse
-
.mold_for(forge_target) ⇒ #call
Get maybe appropriate mold for the given forge target.
-
.wrap_mold(mold) ⇒ #call?
Wrap mold if needed.
Class Method Details
.mold_for(forge_target) ⇒ #call
Get maybe appropriate mold for the given forge target.
Currently provides specific recognition for:
-
subclasses of
Struct(StructMold), -
subclasses of
Data(KeywordsMold), -
Hashand subclasses (HashMold), -
Arrayand subclasses (ArrayMold).
Other objects just get SingleArgumentMold.
134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 |
# File 'lib/object_forge/molds.rb', line 134 def self.mold_for(forge_target) return SingleArgumentMold.new unless ::Class === forge_target mold_class = if forge_target < ::Struct StructMold elsif defined?(::Data) && forge_target < ::Data KeywordsMold elsif forge_target <= ::Hash HashMold elsif forge_target <= ::Array ArrayMold else SingleArgumentMold end mold_class.new end |
.wrap_mold(mold) ⇒ #call?
Wrap mold if needed.
If mold is nil or a callable object, returns it. If it is a Class with #call, wraps it in WrappedMold. Otherwise, raises an error.
166 167 168 169 170 171 172 173 174 |
# File 'lib/object_forge/molds.rb', line 166 def self.wrap_mold(mold) if nil == mold || mold.respond_to?(:call) # rubocop:disable Style/YodaCondition mold # : ObjectForge::mold? elsif ::Class === mold && mold.public_method_defined?(:call) WrappedMold.new(mold) else raise ObjectInterfaceError, "mold must respond to or implement #call" end end |