Skip to content

Instantly share code, notes, and snippets.

@bhauman
Forked from stephencelis/minidress.rb
Created February 11, 2010 03:28
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save bhauman/301173 to your computer and use it in GitHub Desktop.
Save bhauman/301173 to your computer and use it in GitHub Desktop.
Minidress a lightweight factory_girl which will work outside of Rails(I use it with jruby_appengine/Sinatra)
# the more proper miniskirt who doesn't have to walk the rails
class Minidress
@@factories = {}
class << self
def define(name, &block)
@@factories[name.to_s] = block
end
def build(name, attrs = {})
new(get_constant(name).new, &@@factories[name.to_s]).record
end
def attributes_for(name, attrs = {})
build(name, attrs).attributes
end
def create(name, attrs = {})
build(name, attrs).tap { |record| record.save }
end
def get_constant(name_sym)
name = name_sym.to_s.split('_').collect {|s| s.capitalize }.join('')
Object.const_defined?(name) ? Object.const_get(name) : Object.const_missing(name)
end
end
attr_reader :record
def initialize(record)
@record = record and yield self
end
def association(name)
send name, self.class.create(name)
end
def sequence(name)
send name, yield(@n ||= record.class.maximum(:id).to_i + 1, record)
end
private
def method_missing(name, *value)
record.send "#{name}=", *(block_given? ? yield(record) : value)
end
end
def Minidress(name, attrs = {})
Minidress.create(name, attrs)
end
Factory = Minidress
alias Factory Minidress
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment