Class: Factory
Overview
A Factory is a wrapper around a Proc that exposes it through its new method.
Wrapping a Proc in a Factory is useful to have a uniform API across classes and custom object-creating lambdas. For instance, if a method create_object takes a class as argument, like:
def create_object(klass)
obj = klass.new('foo')
# do something with obj
obj
end
you can pass modified class constructors:
create_object(Factory.new {|arg| Array.new(4) { arg } })
and have the method behave as if the passed argument were a normal class.
Instance Attribute Summary collapse
-
#component ⇒ Object
readonly
A Factory can specify a component, which is the class used to instantiate the objects created by this Factory.
Instance Method Summary collapse
-
#__bind__(object) ⇒ Object
Rebind this Factory.
-
#initialize(component = nil, &blk) ⇒ Factory
constructor
Create a factory object.
-
#new(*args) ⇒ Object
Call the wrapped Proc.
Constructor Details
#initialize(component = nil, &blk) ⇒ Factory
Create a factory object.
61 62 63 64 |
# File 'lib/rui/factory.rb', line 61 def initialize(component = nil, &blk) @blk = blk @component = component end |
Instance Attribute Details
#component ⇒ Object (readonly)
A Factory can specify a component, which is the class used to instantiate the objects created by this Factory.
When non-nil, it should satisfy component == new(*args).class
.
53 54 55 |
# File 'lib/rui/factory.rb', line 53 def component @component end |
Instance Method Details
#__bind__(object) ⇒ Object
Rebind this Factory.
Binding a Factory to an object causes the wrapped Proc to be executed in the given object’s scope.
81 82 83 |
# File 'lib/rui/factory.rb', line 81 def __bind__(object) Factory.new(@component, &@blk.bind(object)) end |
#new(*args) ⇒ Object
Call the wrapped Proc
69 70 71 |
# File 'lib/rui/factory.rb', line 69 def new(*args) @blk[*args] end |