Skip to content

Instantly share code, notes, and snippets.

@sideshowcoder
Created June 29, 2012 11:24
Show Gist options
  • Save sideshowcoder/3017432 to your computer and use it in GitHub Desktop.
Save sideshowcoder/3017432 to your computer and use it in GitHub Desktop.
Use ActiveRecord to generate Random Data on a Table
require "active_record"
require "ffaker"
class Post < ActiveRecord::Base
end
class Generator
SQL_TYPE_TO_DATA_MAPPING = {
:varchar => /^varchar\((\d+)\)/,
:text => /^text/
}
# Establish Database connection
def initialize conf_file
config = YAML::load File.open conf_file
ActiveRecord::Base.establish_connection config
end
def generate
# Generate the data table for a Post like { fieldname => sqltype }
column_data = Post.columns_hash.inject({}) do |hash, (key, value)|
hash[key] = value.sql_type
hash
end
Post.create! build_data column_data
end
private
def build_data column_data
column_data.inject({}) do |hash, (field,type)|
Generator::SQL_TYPE_TO_DATA_MAPPING.map do |func,matcher|
if (m = matcher.match type)
if [:varchar].include? func
hash[field] = send func, *m[1]
elsif [:text].include? func
hash[field] = send func, *m[1..2]
else
p m
end
break
end
end
hash
end
end
# Generate random chars with length
def varchar chars
Faker::Lorem.words(30).join[0..chars.to_i]
end
# Generate a Random text
def text
Faker::Lorem.paragraph
end
end
# Connect the Database
generator = Generator.new "database.yml"
# Genearte 100 Records
100.times { generator.generate }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment