Skip to content

Instantly share code, notes, and snippets.

@dam5s
Created January 20, 2013 03:33
Show Gist options
  • Save dam5s/4576524 to your computer and use it in GitHub Desktop.
Save dam5s/4576524 to your computer and use it in GitHub Desktop.
Object Creation Methods to easily make objects for testing, replacing the magic of Factory Girl and still keeping a nice syntax
module ObjectCreationMethods
# def make_user
# def make_user!
define User do
{
username: 'dam5s',
email: '[email protected]',
password: 's0m3pwd',
password_confirmation: 's0m3pwd'
}
end
# def make_robert
# def make_robert!
define User, 'robert' do
{
username: 'robert',
email: '[email protected]',
password: 's0m3pwdForR0b',
password_confirmation: 's0m3pwdForR0b'
}
end
# def make_feed
# def make_feed!
define Feed do
{
name: -> { %w(Twitter Delicious Flickr Blog Tumblr).sample },
url: ->(feed) { "http://example.com/path/to/#{feed.name}.atom" },
default: true
}
end
private
def setup_object(object, attributes, defaults)
defaults.merge(attributes).each do |name, value|
value = value.call(object) if value.respond_to?(:call)
object.send("#{name}=", value)
end
object
end
def self.define(klass, method_name = nil, &block)
method_name ||= klass.to_s.underscore
define_method "make_#{method_name}", ->(attributes = {}) {
defaults = block.call
setup_object(klass.new, attributes, defaults)
}
define_method "make_#{method_name}!", ->(attributes = {}) {
send("make_#{method_name}").tap(&:save!)
}
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment