Created
October 1, 2010 07:22
-
-
Save heycarsten/605876 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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