Module: Machinist::Machinable

Included in:
ActiveRecord::Base
Defined in:
lib/machinist/machinable.rb

Overview

Extend classes with this module to define the blueprint and make methods.

Instance Method Summary collapse

Instance Method Details

#blueprint(name = :master, &block) ⇒ Object

Define a blueprint with the given name for this class.

e.g.

Post.blueprint do
  title { "A Post" }
  body  { "Lorem ipsum..." }
end

If you provide the name argument, a named blueprint will be created. See the blueprint_name argument to the make method.



15
16
17
18
19
20
21
22
# File 'lib/machinist/machinable.rb', line 15

def blueprint(name = :master, &block)
  @blueprints ||= {}
  if block_given?
    parent = (name == :master ? superclass : self) # Where should we look for the parent blueprint?
    @blueprints[name] = blueprint_class.new(self, :parent => parent, &block)
  end
  @blueprints[name]
end

#blueprint_classObject

Classes that include Machinable can override this method if they want to use a custom blueprint class when constructing blueprints.

The default is Machinist::Blueprint.



65
66
67
# File 'lib/machinist/machinable.rb', line 65

def blueprint_class
  Machinist::Blueprint
end

#clear_blueprints!Object

Remove all blueprints defined on this class.



57
58
59
# File 'lib/machinist/machinable.rb', line 57

def clear_blueprints!
  @blueprints = {}
end

#make(*args) ⇒ Object

Construct an object from a blueprint.

:call-seq:

make([count], [blueprint_name], [attributes = {}])
count

The number of objects to construct. If count is provided, make returns an array of objects rather than a single object.

blueprint_name

Construct the object from the named blueprint, rather than the master blueprint.

attributes

Override the attributes from the blueprint with values from this hash.



37
38
39
40
41
# File 'lib/machinist/machinable.rb', line 37

def make(*args)
  decode_args_to_make(*args) do |blueprint, attributes|
    blueprint.make(attributes)
  end
end

#make!(*args) ⇒ Object

Construct and save an object from a blueprint, if the class allows saving.

:call-seq:

make!([count], [blueprint_name], [attributes = {}])

Arguments are the same as for make.



49
50
51
52
53
54
# File 'lib/machinist/machinable.rb', line 49

def make!(*args)
  decode_args_to_make(*args) do |blueprint, attributes|
    raise BlueprintCantSaveError.new(blueprint) unless blueprint.respond_to?(:make!)
    blueprint.make!(attributes)
  end
end