Class: Machinist::Lathe
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
- #assigned_attributes ⇒ Object
-
#initialize(adapter, object, attributes = {}) ⇒ Lathe
constructor
A new instance of Lathe.
- #method_missing(symbol, *args, &block) ⇒ Object
- #object {|@object| ... } ⇒ Object
Constructor Details
#initialize(adapter, object, attributes = {}) ⇒ Lathe
37 38 39 40 41 |
# File 'lib/machinist.rb', line 37 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
48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/machinist.rb', line 48 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) && !nil_or_empty?(@object.send(symbol)) # 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 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 |
# File 'lib/machinist.rb', line 9 def self.run(adapter, object, *args) if args.first.is_a?(Symbol) name = args.shift named_blueprint = object.class.blueprint(name) raise "No blueprint named '#{name}' defined for class #{object.class}" if named_blueprint.nil? end blueprint = object.class.blueprint if blueprint.nil? if named_blueprint raise "Can't construct an object from a named blueprint without a default blueprint for class #{object.class}" else raise "No blueprint for class #{object.class}" end end attributes = args.pop || {} lathe = self.new(adapter, object, attributes) lathe.instance_eval(&named_blueprint) if named_blueprint klass = object.class while klass lathe.instance_eval(&klass.blueprint) if klass.respond_to?(:blueprint) && klass.blueprint klass = klass.superclass end lathe end |