Class: Machinist::Blueprint

Inherits:
Object
  • Object
show all
Defined in:
lib/machinist/blueprint.rb

Overview

A Blueprint defines a method of constructing objects of a particular class.

Direct Known Subclasses

ActiveRecord::Blueprint

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(klass, options = {}, &block) ⇒ Blueprint

Construct a blueprint for the given klass.

Pass in the :parent option to define a parent blueprint to apply after this one. You can supply another blueprint, or a class in which to look for a blueprint. In the latter case, make will walk up the superclass chain looking for blueprints to apply.



10
11
12
13
14
# File 'lib/machinist/blueprint.rb', line 10

def initialize(klass, options = {}, &block)
  @klass  = klass
  @parent = options[:parent]
  @block  = block
end

Instance Attribute Details

#blockObject (readonly)

Returns the value of attribute block.



16
17
18
# File 'lib/machinist/blueprint.rb', line 16

def block
  @block
end

#klassObject (readonly)

Returns the value of attribute klass.



16
17
18
# File 'lib/machinist/blueprint.rb', line 16

def klass
  @klass
end

#parentObject (readonly)

Returns the value of attribute parent.



16
17
18
# File 'lib/machinist/blueprint.rb', line 16

def parent
  @parent
end

Instance Method Details

#each_ancestorObject

Yields the parent blueprint, its parent blueprint, etc.



52
53
54
55
56
57
58
# File 'lib/machinist/blueprint.rb', line 52

def each_ancestor
  ancestor = parent_blueprint
  while ancestor
    yield ancestor
    ancestor = ancestor.parent_blueprint
  end
end

#lathe_classObject

Returns the Lathe class used to make objects for this blueprint.

Subclasses can override this to substitute a custom lathe class.



33
34
35
# File 'lib/machinist/blueprint.rb', line 33

def lathe_class
  Lathe
end

#make(attributes = {}) ⇒ Object

Generate an object from this blueprint.

Pass in attributes to override values defined in the blueprint.



21
22
23
24
25
26
27
28
# File 'lib/machinist/blueprint.rb', line 21

def make(attributes = {})
  lathe = lathe_class.new(@klass, new_serial_number, attributes)

  lathe.instance_eval(&@block)
  each_ancestor { |blueprint| lathe.instance_eval(&blueprint.block) }

  lathe.object
end

#parent_blueprintObject

Returns the parent blueprint for this blueprint.



38
39
40
41
42
43
44
45
46
47
48
49
# File 'lib/machinist/blueprint.rb', line 38

def parent_blueprint
  case @parent
  when nil
    nil
  when Blueprint
    # @parent references the parent blueprint directly.
    @parent
  else
    # @parent is a class in which we should look for a blueprint.
    find_blueprint_in_superclass_chain(@parent)
  end
end