Class: Factory

Inherits:
Object show all
Defined in:
lib/rui/factory.rb

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

Instance Method Summary collapse

Constructor Details

#initialize(component = nil, &blk) ⇒ Factory

Create a factory object.

Parameters:

  • component (Class) (defaults to: nil)

    the factory component

  • &blk

    the wrapped Proc



61
62
63
64
# File 'lib/rui/factory.rb', line 61

def initialize(component = nil, &blk)
  @blk = blk
  @component = component
end

Instance Attribute Details

#componentObject (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.

Returns:

  • the component of this Factory



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.

Parameters:

  • object

    the object to bind this Factory to



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