class Factory

Factory girl, relaxed.

Factory.define :user do |f|
  f.login 'johndoe%d'                          # Sequence.
  f.email '%{login}@example.com'               # Interpolate.
  f.password f.password_confirmation('foobar') # Chain.
end

Factory.define :post do |f|
  f.user { Factory :user }                     # Blocks, if you must.
end

Public Class Methods

build(name, attrs = {}) click to toggle source
# File minifacture.rb, line 23
def build name, attrs = {}
  (h, opts, n = @@attrs[name = name.to_s]) and m = opts[:class] || name
  p = opts[:parent] and (h, m = @@attrs[p = p.to_s][0].merge(h), p)
  (m = m.is_a?(Class) ? m : m.to_s.camelize.constantize).new.tap do |r|
    c = @@counts[p || name] += 1
    attrs.symbolize_keys!.reverse_update(h).each do |k, v|
      r.send "#{k}=", case v when String # Sequence and interpolate.
        v.sub(/%\d*d/) { |d| d % n ||= c } % attrs % n
      when Proc then v.call(r) else v
      end
    end
  end
end
create(name, attrs = {}) click to toggle source
# File minifacture.rb, line 37
def create name, attrs = {}
  build(name, attrs).tap { |record| record.save! }
end
define(name, options = {}) { |new(name)| ... } click to toggle source
# File minifacture.rb, line 19
def define name, options = {}
  @@attrs[name = name.to_s] = [{}, options] and yield new(name)
end

Public Instance Methods

method_missing(name, value = nil, &block) click to toggle source
# File minifacture.rb, line 42
def method_missing name, value = nil, &block
  @@attrs[__klass__][0][name] = block || value
end