Skip to content

Instantly share code, notes, and snippets.

@jugyo
Created November 7, 2012 05:54
Show Gist options
  • Save jugyo/4029778 to your computer and use it in GitHub Desktop.
Save jugyo/4029778 to your computer and use it in GitHub Desktop.
ActiveRecord extension to print FactoryGirl definition!
class ActiveRecord::Base
# Usage:
#
# > puts User.first.to_factory_girl
# FactoryGirl.define do
# factory :user do
# ...
# end
# end
# # Usage: FactoryGirl.create(:user, ...)
def to_factory_girl
ignores = %w(id created_at updated_at)
array = []
array << "# encoding: utf-8"
array << "FactoryGirl.define do"
factory_name = self.class.model_name.underscore
unless factory_name =~ %r|/|
array << " factory :#{factory_name} do"
else
factory_name.gsub!('/', '_')
array << " factory :#{factory_name}, :class => #{self.class.name} do"
end
attributes.each do |key, value|
next if ignores.include?(key)
if key =~ /_id$/
array << " association :#{key.gsub(/_id$/, '')}"
else
array << " #{key} #{value.inspect}"
end
end
array << " end"
array << "end"
usage = ""
usage << "# Usage: FactoryGirl.create(:#{factory_name}"
attributes.each do |key, value|
next if ignores.include?(key)
if key =~ /_id$/
factory_name = key.gsub(/_id$/, '')
usage << ", #{factory_name}: FactoryGirl.create(:#{factory_name})"
else
usage << ", #{key}: #{value.inspect}"
end
end
usage << ")"
array << usage
array.join("\n")
end
alias_method :to_fg, :to_factory_girl
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment