Module: Spawn

Defined in:
lib/spawn.rb

Defined Under Namespace

Classes: Invalid

Instance Method Summary collapse

Instance Method Details

#spawn(params = {}) {|model| ... } ⇒ Object

Yields:

  • (model)


12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/spawn.rb', line 12

def spawn params = {}

  # Grab default parameters from spawner block.
  @@spawn[self].call(attrs = OpenStruct.new(params))

  # Initialize model
  model = new(attrs.send(:table).merge(params))

  # Yield model for changes to be made before saving.
  yield(model) if block_given?

  # Raise an error if the model is invalid or couldn't be saved.
  model.valid? and model.save and model or raise(Invalid, model.errors.inspect)
end

#spawner(&default) ⇒ Object



7
8
9
10
# File 'lib/spawn.rb', line 7

def spawner &default
  @@spawn ||= Hash.new
  @@spawn[self] = default
end