Class: Machinist::Lathe

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

Overview

A Lathe is used to execute the blueprint and construct an object.

The blueprint is instance_eval’d against the Lathe.

Class Method Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(adapter, object, attributes = {}) ⇒ Lathe

Returns a new instance of Lathe.



20
21
22
23
24
# File 'lib/machinist.rb', line 20

def initialize(adapter, object, attributes = {})
  @adapter = adapter
  @object  = object
  attributes.each {|key, value| assign_attribute(key, value) }
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(symbol, *args, &block) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
# File 'lib/machinist.rb', line 31

def method_missing(symbol, *args, &block)
  if attribute_assigned?(symbol)
    # If we've already assigned the attribute, return that.
    @object.send(symbol)
  elsif @adapter.has_association?(@object, symbol) && !@object.send(symbol).nil?
    # If the attribute is an association and is already assigned, return that.
    @object.send(symbol)
  else
    # Otherwise generate a value and assign it.
    assign_attribute(symbol, generate_attribute_value(symbol, *args, &block))
  end
end

Class Method Details

.run(adapter, object, *args) ⇒ Object



9
10
11
12
13
14
15
16
17
18
# File 'lib/machinist.rb', line 9

def self.run(adapter, object, *args)
  blueprint       = object.class.blueprint
  named_blueprint = object.class.blueprint(args.shift) if args.first.is_a?(Symbol)
  attributes      = args.pop || {}
  raise "No blueprint for class #{object.class}" if blueprint.nil?
  returning self.new(adapter, object, attributes) do |lathe|
    lathe.instance_eval(&named_blueprint) if named_blueprint
    lathe.instance_eval(&blueprint)
  end
end

Instance Method Details

#assigned_attributesObject



44
45
46
# File 'lib/machinist.rb', line 44

def assigned_attributes
  @assigned_attributes ||= {}
end

#object {|@object| ... } ⇒ Object

Yields:



26
27
28
29
# File 'lib/machinist.rb', line 26

def object
  yield @object if block_given?
  @object
end