Skip to content

Commit

Permalink
improving documentation
Browse files Browse the repository at this point in the history
  • Loading branch information
ryanb committed Sep 1, 2008
1 parent ee310d3 commit c2835f7
Show file tree
Hide file tree
Showing 9 changed files with 163 additions and 48 deletions.
6 changes: 4 additions & 2 deletions CHANGELOG
@@ -1,3 +1,5 @@
* improving inline documentation

*0.2.1* (August 30th, 2008)

* wrap sqlite inserts in transaction to improve performance
Expand All @@ -10,9 +12,9 @@

* improving performance when nesting factories

* adding Populate.sentences to generate a lot of text
* adding Populator.sentences to generate a lot of text

* adding Populate.words to fetch some random words
* adding Populator.words to fetch some random words

*0.1.0* (August 27th, 2008)

Expand Down
1 change: 1 addition & 0 deletions Manifest
Expand Up @@ -9,6 +9,7 @@ lib/populator.rb
LICENSE
Manifest
populator.gemspec
Rakefile
README
spec/database.yml
spec/example_database.yml
Expand Down
6 changes: 3 additions & 3 deletions README
Expand Up @@ -10,7 +10,7 @@ this code is loosely based on.

Install the gem:

gem install ryanb-populator --source http://gems.github.com
gem install populator

And then load it in your project:

Expand Down Expand Up @@ -64,7 +64,7 @@ If you need to generate fake data, there are a few methods to do this.

For fancier data generation, try the Faker gem.

http://faker.rubyforge.org
http://faker.rubyforge.org


== Important
Expand All @@ -80,7 +80,7 @@ See spec/README for instructions on running specs.

This project can be found on github at the following URL.

http://github.com/ryanb/populator/
http://github.com/ryanb/populator

If you would like to contribute to this project, please fork the
repository and send me a pull request.
4 changes: 4 additions & 0 deletions lib/populator.rb
Expand Up @@ -6,3 +6,7 @@

require 'populator/adapters/abstract'
require 'populator/adapters/sqlite'

# Populator is made up of several parts. To start, see Populator::ModelAdditions.
module Populator
end
13 changes: 13 additions & 0 deletions lib/populator/factory.rb
@@ -1,39 +1,51 @@
module Populator
# Builds multiple Populator::Record instances and saves them to the database
class Factory
DEFAULT_RECORDS_PER_QUERY = 1000

@factories = {}
@depth = 0

# Fetches the factory dedicated to a given model class. You should always use this
# method instead of instatiating a factory directly so that a single factory is
# shared on multiple calls.
def self.for_model(model_class)
@factories[model_class] ||= new(model_class)
end

# Find all remaining factories and call save_records on them.
def self.save_remaining_records
@factories.values.each do |factory|
factory.save_records
end
@factories = {}
end

# Keep track of nested factory calls so we can save the remaining records once we
# are done with the base factory. This makes Populator more efficient when nesting
# factories.
def self.remember_depth
@depth += 1
yield
@depth -= 1
save_remaining_records if @depth.zero?
end

# Use for_model instead of instatiating a record directly.
def initialize(model_class)
@model_class = model_class
@records = []
end

# Entry method for building records. Delegates to build_records after remember_depth.
def populate(amount, options = {}, &block)
self.class.remember_depth do
build_records(Populator.interpret_value(amount), options[:per_query] || DEFAULT_RECORDS_PER_QUERY, &block)
end
end

# Builds multiple Populator::Record instances and calls save_records them when
# :per_query limit option is reached.
def build_records(amount, per_query, &block)
amount.times do
record = Record.new(@model_class, last_id_in_database + @records.size + 1)
Expand All @@ -43,6 +55,7 @@ def build_records(amount, per_query, &block)
end
end

# Saves the records to the database by calling populate on the current database adapter.
def save_records
unless @records.empty?
@model_class.connection.populate(@model_class.quoted_table_name, columns_sql, rows_sql_arr, "#{@model_class.name} Populate")
Expand Down
21 changes: 21 additions & 0 deletions lib/populator/model_additions.rb
@@ -1,5 +1,26 @@
module Populator
module ModelAdditions
# Call populate on any ActiveRecord model to fill it with data.
# Pass the number of records you want to create, and a block to
# set the attributes. You can nest calls to handle associations
# and use ranges or arrays to randomize the values.
#
# Person.populate(3000) do |person|
# person.name = "John Doe"
# person.gender = ['male', 'female']
# Project.populate(10..30, :per_query => 100) do |project|
# project.person_id = person.id
# project.due_at = 5.days.from_now..2.years.from_now
# project.name = Populator.words(1..3).titleize
# project.description = Populator.sentences(2..10)
# end
# end
#
# The following options are supported.
#
# * <tt>:per_query</tt> - limit how many records are inserted per query, defaults to 1000
#
# Populator::Factory is where all the work happens.
def populate(amount, options = {}, &block)
Factory.for_model(self).populate(amount, options, &block)
end
Expand Down
9 changes: 9 additions & 0 deletions lib/populator/random.rb
@@ -1,7 +1,10 @@
module Populator
# This module adds several methods for generating random data which can be
# called directly on Populator.
module Random
WORDS = %w(alias consequatur aut perferendis sit voluptatem accusantium doloremque aperiam eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt explicabo aspernatur aut odit aut fugit sed quia consequuntur magni dolores eos qui ratione voluptatem sequi nesciunt neque dolorem ipsum quia dolor sit amet consectetur adipisci velit sed quia non numquam eius modi tempora incidunt ut labore et dolore magnam aliquam quaerat voluptatem ut enim ad minima veniam quis nostrum exercitationem ullam corporis nemo enim ipsam voluptatem quia voluptas sit suscipit laboriosam nisi ut aliquid ex ea commodi consequatur quis autem vel eum iure reprehenderit qui in ea voluptate velit esse quam nihil molestiae et iusto odio dignissimos ducimus qui blanditiis praesentium laudantium totam rem voluptatum deleniti atque corrupti quos dolores et quas molestias excepturi sint occaecati cupiditate non provident sed ut perspiciatis unde omnis iste natus error similique sunt in culpa qui officia deserunt mollitia animi id est laborum et dolorum fuga et harum quidem rerum facilis est et expedita distinctio nam libero tempore cum soluta nobis est eligendi optio cumque nihil impedit quo porro quisquam est qui minus id quod maxime placeat facere possimus omnis voluptas assumenda est omnis dolor repellendus temporibus autem quibusdam et aut consequatur vel illum qui dolorem eum fugiat quo voluptas nulla pariatur at vero eos et accusamus officiis debitis aut rerum necessitatibus saepe eveniet ut et voluptates repudiandae sint et molestiae non recusandae itaque earum rerum hic tenetur a sapiente delectus ut aut reiciendis voluptatibus maiores doloribus asperiores repellat)

# Pick a random value out of a given range.
def value_in_range(range)
case range.first
when Integer then number_in_range(range)
Expand All @@ -11,16 +14,22 @@ def value_in_range(range)
end
end

# Generate a given number of words. If a range is passed, it will generate
# a random number of words within that range.
def words(total)
(1..interpret_value(total)).map { WORDS.rand }.join(' ')
end

# Generate a given number of sentences. If a range is passed, it will generate
# a random number of sentences within that range.
def sentences(total)
(1..interpret_value(total)).map do
words(5..20).capitalize
end.join('. ')
end

# If an array or range is passed, a random value will be selected to match.
# All other values are simply returned.
def interpret_value(value)
case value
when Array then value.rand
Expand Down
10 changes: 10 additions & 0 deletions lib/populator/record.rb
@@ -1,7 +1,16 @@
module Populator
# This is what is passed to the block when calling populate.
class Record
attr_accessor :attributes

# Creates a new instance of Record and generates some accessor
# methods for setting attributes. Some attributes are set by default:
#
# * <tt>id</tt> - defaults to id passed
# * <tt>created_at</tt> - defaults to current time
# * <tt>updated_at</tt> - defaults to current time
# * <tt>created_on</tt> - defaults to current date
# * <tt>updated_on</tt> - defaults to current date
def initialize(model_class, id)
@attributes = { :id => id }
@columns = model_class.column_names
Expand All @@ -24,6 +33,7 @@ def #{column}
end
end

# Return values for all columns inside an array.
def attribute_values
@columns.map do |column|
@attributes[column.to_sym]
Expand Down
141 changes: 98 additions & 43 deletions populator.gemspec
Expand Up @@ -2,50 +2,105 @@
# Gem::Specification for Populator-0.2.1
# Originally generated by Echoe

Gem::Specification.new do |s|
s.name = %q{populator}
s.version = "0.2.1"
--- !ruby/object:Gem::Specification
name: populator
version: !ruby/object:Gem::Version
version: 0.2.1
platform: ruby
authors:
- Ryan Bates
autorequire:
bindir: bin

s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
s.authors = ["Ryan Bates"]
s.date = %q{2008-08-30}
s.description = %q{Mass populate an Active Record database.}
s.email = %q{ryan (at) railscasts (dot) com}
s.extra_rdoc_files = ["CHANGELOG", "lib/populator/adapters/abstract.rb", "lib/populator/adapters/sqlite.rb", "lib/populator/factory.rb", "lib/populator/model_additions.rb", "lib/populator/random.rb", "lib/populator/record.rb", "lib/populator.rb", "LICENSE", "README", "tasks/deployment.rake", "tasks/spec.rake", "TODO"]
s.files = ["CHANGELOG", "lib/populator/adapters/abstract.rb", "lib/populator/adapters/sqlite.rb", "lib/populator/factory.rb", "lib/populator/model_additions.rb", "lib/populator/random.rb", "lib/populator/record.rb", "lib/populator.rb", "LICENSE", "Manifest", "populator.gemspec", "README", "spec/database.yml", "spec/example_database.yml", "spec/models/category.rb", "spec/models/product.rb", "spec/populator/factory_spec.rb", "spec/populator/model_additions_spec.rb", "spec/populator/random_spec.rb", "spec/populator/record_spec.rb", "spec/README", "spec/spec.opts", "spec/spec_helper.rb", "tasks/deployment.rake", "tasks/spec.rake", "TODO"]
s.has_rdoc = true
s.homepage = %q{http://github.com/ryanb/populator}
s.rdoc_options = ["--line-numbers", "--inline-source", "--title", "Populator", "--main", "README"]
s.require_paths = ["lib"]
s.rubyforge_project = %q{populator}
s.rubygems_version = %q{1.2.0}
s.summary = %q{Mass populate an Active Record database.}
date: 2008-09-01 00:00:00 -07:00
default_executable:
dependencies:
- !ruby/object:Gem::Dependency
name: echoe
type: :development
version_requirement:
version_requirements: !ruby/object:Gem::Requirement
requirements:
- - ">="
- !ruby/object:Gem::Version
version: "0"
version:
description: Mass populate an Active Record database.
email: ryan (at) railscasts (dot) com
executables: []

if s.respond_to? :specification_version then
current_version = Gem::Specification::CURRENT_SPECIFICATION_VERSION
s.specification_version = 2
extensions: []

if current_version >= 3 then
else
end
else
end
end
extra_rdoc_files:
- CHANGELOG
- lib/populator/adapters/abstract.rb
- lib/populator/adapters/sqlite.rb
- lib/populator/factory.rb
- lib/populator/model_additions.rb
- lib/populator/random.rb
- lib/populator/record.rb
- lib/populator.rb
- LICENSE
- README
- tasks/deployment.rake
- tasks/spec.rake
- TODO
files:
- CHANGELOG
- lib/populator/adapters/abstract.rb
- lib/populator/adapters/sqlite.rb
- lib/populator/factory.rb
- lib/populator/model_additions.rb
- lib/populator/random.rb
- lib/populator/record.rb
- lib/populator.rb
- LICENSE
- Manifest
- Rakefile
- README
- spec/database.yml
- spec/example_database.yml
- spec/models/category.rb
- spec/models/product.rb
- spec/populator/factory_spec.rb
- spec/populator/model_additions_spec.rb
- spec/populator/random_spec.rb
- spec/populator/record_spec.rb
- spec/README
- spec/spec.opts
- spec/spec_helper.rb
- tasks/deployment.rake
- tasks/spec.rake
- TODO
- populator.gemspec
has_rdoc: true
homepage: http://github.com/ryanb/populator
post_install_message:
rdoc_options:
- --line-numbers
- --inline-source
- --title
- Populator
- --main
- README
require_paths:
- lib
required_ruby_version: !ruby/object:Gem::Requirement
requirements:
- - ">="
- !ruby/object:Gem::Version
version: "0"
version:
required_rubygems_version: !ruby/object:Gem::Requirement
requirements:
- - "="
- !ruby/object:Gem::Version
version: "1.2"
version:
requirements: []


# # Original Rakefile source (requires the Echoe gem):
#
# require 'rubygems'
# require 'rake'
# require 'echoe'
#
# Echoe.new('populator', '0.2.1') do |p|
# p.summary = "Mass populate an Active Record database."
# p.description = "Mass populate an Active Record database."
# p.url = "http://github.com/ryanb/populator"
# p.author = 'Ryan Bates'
# p.email = "ryan (at) railscasts (dot) com"
# p.ignore_pattern = ["script/*", "**/*.sqlite3"]
# end
#
# Dir["#{File.dirname(__FILE__)}/tasks/*.rake"].sort.each { |ext| load ext }
rubyforge_project: populator
rubygems_version: 1.2.0
specification_version: 2
summary: Mass populate an Active Record database.
test_files: []

0 comments on commit c2835f7

Please sign in to comment.