Skip to content

Instantly share code, notes, and snippets.

@heycarsten
Created October 1, 2010 07:22
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save heycarsten/605876 to your computer and use it in GitHub Desktop.
Save heycarsten/605876 to your computer and use it in GitHub Desktop.
# I wanted a simple object factory for use with Ohm, I'm used to factory_girl
# and fabrication. After a few minutes of messing around and trying to get them
# to work with Ohm, I decided to try giving it a whirl myself...
class Factory
def self.factories
@factories ||= {}
end
def self.define(model, &block)
factories[model] = begin
factory = new
factory.instance_eval(&block)
factory
end
end
def self.build(model, overloads = {})
factory = factories[model]
raise ArgumentError, "There is no factory for #{model} yet." unless factory
model.new(factory.defaults.merge(overloads))
end
def self.create(model, overloads = {})
instance = build(model, overloads)
instance.save
instance
end
attr_reader :defaults
def initialize
@defaults = {}
end
def method_missing(name, value)
defaults[name] = value
end
end
def Factory(*args)
Factory.create(*args)
end
# Usage:
#
# class Tree < Ohm::Model
# attribute :name
# attribute :height
# end
#
# Factory.define(Tree) do
# name 'Pine'
# height '22 feet'
# end
#
# @tree = Factory(Tree, :name => 'Maple')
#
# Anyways, obvs this implementation is limited but can be easily extended. I
# just thought you might find it interesting.
#
# Carsten
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment