Class: Sequel::Model

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

Class Attribute Summary collapse

Class Method Summary collapse

Class Attribute Details

.factory_methodObject

Returns the name of the Sequel::Model class method that this factory uses to make new instances. Defaults to :create. Other useful methods are :new (to prevent saving to the database) and :find_or_create (to avoid violating uniqueness constraints in the database).



68
69
70
71
72
# File 'lib/sequel/factory.rb', line 68

def self.factory_method
  return @factory_method unless @factory_method.nil?
  return superclass.factory_method if superclass.respond_to?(:factory_method)
  :create
end

Class Method Details

.build(*args) ⇒ Object

Sugar for make_with(:new, *args). Useful when the #factory_method is something other than :new but you still want to use it.



119
120
121
# File 'lib/sequel/factory.rb', line 119

def self.build(*args)
  make_with(:new, *args)
end

.factoriesObject

A Hash of factories for this model, keyed by factory name.



75
76
77
# File 'lib/sequel/factory.rb', line 75

def self.factories
  @factories ||= {}
end

.factory(name = :default) ⇒ Object

Gets/sets the factory with the given name. If a block is given, uses that block to create a new factory.



81
82
83
84
# File 'lib/sequel/factory.rb', line 81

def self.factory(name=:default)
  factories[name] = Factory.new(Proc.new) if block_given?
  factories[name]
end

.has_factory?(name) ⇒ Boolean

Returns:

  • (Boolean)


86
87
88
# File 'lib/sequel/factory.rb', line 86

def self.has_factory?(name)
  not factory(name).nil?
end

.make(*factory_names) ⇒ Object

Makes an instance of this model using the factories with the given factory_names. If a Hash is given as the last argument it is used to override any factory-produced values with the same name after all factory values have been generated. The default factory is used if no factory names are given.



95
96
97
98
99
100
101
102
103
104
105
# File 'lib/sequel/factory.rb', line 95

def self.make(*factory_names)
  values = Hash === factory_names.last ? factory_names.pop : Hash.new
  factory_names << :default if factory_names.empty?

  factory_values = factory_names.inject({}) do |memo, name|
    fac = factory(name) or raise "Unknown #{self} factory: #{name}"
    fac.apply_values(memo)
  end

  send factory_method, factory_values.merge(values)
end

.make_with(method, *args) ⇒ Object

Forces the #factory_method to be the given method temporarily while an instance is made, then reverts to the old factory method.



109
110
111
112
113
114
115
# File 'lib/sequel/factory.rb', line 109

def self.make_with(method, *args)
  tmp = @factory_method
  @factory_method = method
  obj = make(*args)
  @factory_method = tmp
  obj
end