Class: Sequel::Factory

Inherits:
Object
  • Object
show all
Defined in:
lib/cutest/database/sequel_factories.rb

Instance Attribute Summary collapse

Instance Method Summary collapse

Constructor Details

#initialize(values_proc) ⇒ Factory

Returns a new instance of Factory.



5
6
7
# File 'lib/cutest/database/sequel_factories.rb', line 5

def initialize(values_proc)
  @values_proc = values_proc
end

Dynamic Method Handling

This class handles dynamic methods through the method_missing method

#method_missing(key, *args) ⇒ Object

Gets/sets the value of the given key. If any args are provided, the value is set to the first one. Otherwise, if a block is given it will be called with a number unique to the given key (like a sequence) and the return value of the block is used as the value.



45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/cutest/database/sequel_factories.rb', line 45

def method_missing(key, *args)
  if args.any?
    @values[key] = args.first
  elsif block_given?
    @counts ||= {}
    @counts[key] ||= 0
    @counts[key] += 1
    @values[key] = yield(@counts[key])
  end

  @values[key]
end

Instance Attribute Details

#values_procObject (readonly)

The Proc this factory uses to generate a new set of values.



10
11
12
# File 'lib/cutest/database/sequel_factories.rb', line 10

def values_proc
  @values_proc
end

Instance Method Details

#apply_values(values = {}) ⇒ Object

Merges all key/value pairs generated by this factory into the given values hash.



14
15
16
17
18
# File 'lib/cutest/database/sequel_factories.rb', line 14

def apply_values(values={})
  @values = values
  instance_eval(&values_proc)
  @values
end

#include_factory(factory) ⇒ Object Also known as: include

Merges all key/value pairs that are generated by the given factory into the values currently being generated by this factory. Should be called inside a values Proc to include values from some higher-level factory.

User.factory do
  name Randgen.name
end

User.factory(:with_url) do
  include_factory User.factory
  url "http://www.example.com"
end

User.make               # Has only a name property
User.make(:with_url)    # Has both name *and* url properties


35
36
37
# File 'lib/cutest/database/sequel_factories.rb', line 35

def include_factory(factory)
  factory.apply_values(@values)
end