Class: Factory::Builder

Inherits:
Object
  • Object
show all
Defined in:
lib/rspec_ext/factory.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(name, options = {}, &initializer) ⇒ Builder

Returns a new instance of Builder.



9
10
11
12
13
14
15
# File 'lib/rspec_ext/factory.rb', line 9

def initialize name, options = {}, &initializer
  @initializer = initializer
  @klass, @parent = options[:class], options[:parent]
  unless klass or parent or initializer
    raise "there are nor class nor initializer nor parent provided for :#{name}!"
  end
end

Instance Attribute Details

#initializerObject (readonly)

Returns the value of attribute initializer.



7
8
9
# File 'lib/rspec_ext/factory.rb', line 7

def initializer
  @initializer
end

#klassObject (readonly)

Returns the value of attribute klass.



7
8
9
# File 'lib/rspec_ext/factory.rb', line 7

def klass
  @klass
end

#nameObject (readonly)

Returns the value of attribute name.



7
8
9
# File 'lib/rspec_ext/factory.rb', line 7

def name
  @name
end

#parentObject (readonly)

Returns the value of attribute parent.



7
8
9
# File 'lib/rspec_ext/factory.rb', line 7

def parent
  @parent
end

Instance Method Details

#build(attributes = {}, &block) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
# File 'lib/rspec_ext/factory.rb', line 17

def build attributes = {}, &block
  if parent
    o = factory.build parent
    initializer.call o if initializer
  elsif klass
    real_class = self.klass.is_a?(String) ? self.klass.constantize : self.klass
    o = real_class.new
    initializer.call o if initializer
  elsif initializer
    o = initializer.call
  end

  attributes.each{|name, value| o.send :"#{name}=", value}
  block.call o if block

  o
end