Created
March 21, 2012 14:12
-
-
Save rondale-sc/2147189 to your computer and use it in GitHub Desktop.
Generate sample file
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
require 'rubygems' | |
require 'mysql2' | |
require 'faker' | |
require 'pry' | |
class SampleData | |
attr_reader :connection | |
def initialize(size) | |
@sample_size = size || 1000 | |
@connection = Mysql2::Client.new(:host => "localhost", :username => "root", :password => "password") | |
end | |
def create_row | |
sql = """ | |
INSERT INTO `ruby_test`.`demographics` (first_name, | |
last_name, | |
email, | |
address, | |
city, | |
state, | |
zip, | |
created_at, | |
updated_at) | |
VALUES ('#{e Faker::Name.first_name}', | |
'#{e Faker::Name.last_name}', | |
'#{e Faker::Internet.email}', | |
'#{e Faker::Address.street_address}', | |
'#{e Faker::Address.city}', | |
'#{e Faker::Address.state_abbr}', | |
'#{e Faker::Address.zip_code}', | |
'#{Time.now}', | |
'#{Time.now}' | |
); | |
""" | |
connection.query sql | |
end | |
# Escape unsafe strings. e as helper (find in SampleData#create_row) | |
def e (str) | |
connection.escape str | |
end | |
def create_database | |
connection.query "CREATE database ruby_test;" | |
end | |
def create_table | |
connection.query "CREATE TABLE `ruby_test`.`demographics` (first_name VARCHAR(255), last_name VARCHAR(255), | |
email VARCHAR(255), address VARCHAR(255), city VARCHAR(255), | |
state VARCHAR(255), zip VARCHAR(255), created_at TIMESTAMP, | |
updated_at TIMESTAMP | |
);" | |
end | |
def drop_table | |
connection.query "DROP TABLE `ruby_test`.`demographics`;" | |
end | |
def generate_sample | |
drop_table | |
create_table | |
@sample_size.times do |row| | |
create_row | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
LIttle script for creating sample data. Useful for testing your db. (in my case a potential switch to percona)