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
-
#blueprint(name = :master, &block) ⇒ Object
Define a blueprint with the given name for this class.
-
#blueprint_class ⇒ Object
Classes that include Machinable can override this method if they want to use a custom blueprint class when constructing blueprints.
-
#clear_blueprints! ⇒ Object
Remove all blueprints defined on this class.
-
#make(*args) ⇒ Object
Construct an object from a blueprint.
-
#make!(*args) ⇒ Object
Construct and save an object from a blueprint, if the class allows saving.
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.
14 15 16 17 18 19 20 21 |
# File 'lib/machinist/machinable.rb', line 14 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_class ⇒ Object
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.
64 65 66 |
# File 'lib/machinist/machinable.rb', line 64 def blueprint_class Machinist::Blueprint end |
#clear_blueprints! ⇒ Object
Remove all blueprints defined on this class.
56 57 58 |
# File 'lib/machinist/machinable.rb', line 56 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.
36 37 38 39 40 |
# File 'lib/machinist/machinable.rb', line 36 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.
48 49 50 51 52 53 |
# File 'lib/machinist/machinable.rb', line 48 def make!(*args) decode_args_to_make(*args) do |blueprint, attributes| raise BlueprintCantSaveError, blueprint unless blueprint.respond_to?(:make!) blueprint.make!(attributes) end end |