Skip to content

Instantly share code, notes, and snippets.

@josephholsten
Last active December 10, 2015 13:28
Show Gist options
  • Save josephholsten/4441216 to your computer and use it in GitHub Desktop.
Save josephholsten/4441216 to your computer and use it in GitHub Desktop.
because creating fake data is annoying
class Date
def self.random(from=Date.new(1970), to=Time.now.to_date)
rand(from..to)
end
end
module ActiveRecord
class Base
def self.fake_attributes(use_nulls=false)
Hash[self.columns.map {|c| c.random_record(use_nulls) }]
end
end
class ConnectionAdapters::Column
def random_record(use_nulls=false)
require 'faker'
value = if self.null and use_nulls
nil
else
case self.type
when :integer
(rand * 10**self.limit).to_i
when :boolean
(rand >= 0.5) ? true : false
when :datetime, :date, :time
Date.random
when :string
case self.name
when /first_name/
Faker::Name.first_name
when /last_name/
Faker::Name.last_name
when /city/
Faker::Address.city
when /country/
Faker::Address.country
when /state/
Faker::Address.state
when /zip|zip.*code|post.*code/
Faker::Address.postcode
when /phone|fax/
Faker::PhoneNumber.phone_number
when /email/
Faker::Internet.email
when /name/
# likely for false positives, leave almost last
Faker::Name.name
else
Faker::Base.letterify('?' * (rand * 64))
end
else
self.type
end
end
[self.name, value]
end
end
end
3
#
# Examples
#
# require 'fakify'
#
# # create a hash with random values for all the columns in a company
# Company.fake_attributes
#
# # create a new company with all random values
# Company.new(Company.fake_attributes)
#
# # create a new company with random values for all columns with the NOT NULL constraint
# Company.new(Company.fake_attributes(true))
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment