seed_dump 2.0.0 → 3.0.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
checksums.yaml CHANGED
@@ -1,7 +1,7 @@
1
1
  ---
2
2
  SHA1:
3
- metadata.gz: 1a7a3bc7780fa30de0f2ffccb171249879058fa5
4
- data.tar.gz: dad1c603abb084874344d01263e6dae6d88ea03d
3
+ metadata.gz: 616a5857e516b0f3dbeacfa6ccc958481edd2af3
4
+ data.tar.gz: d92c064c2970dc8ea0743a57db2749721a9a501e
5
5
  SHA512:
6
- metadata.gz: 9e1f0bfa9e904d6b0b6756b45caa39afee9576f5661c155485d23f430ff87509f488f6b95e247e4ede7f3b41171229b9e49e989677acb3b658be5345e343f4d5
7
- data.tar.gz: 74606c3f956c8b5118e83edea597f152e8e02b7913ee1af6ffcba3f9c63f0700d0f34042bfe50f2e536b72b29bfcb1a27d4c58682d9f16926b3699ff7afe1655
6
+ metadata.gz: 46f9fcdcb191fef7bfd6c880662bc3a4ac2b84ae29d82d8d2d5dc24095117d074c7d2d27c50670530ce929fd1b21d5a71297b0b3cc173eb3aa7745126991c093
7
+ data.tar.gz: d141c0da2700d4cf927f10ec7e46b64e2a53e5df7a85addc00ac4ead7fbebbc9feebe761d2d8460c3254278bcc893126a9e84e66be4aa98c70ca5ea818fe4aee
data/Gemfile CHANGED
@@ -5,6 +5,7 @@ gem 'activerecord'
5
5
 
6
6
  group :development, :test do
7
7
  gem 'byebug'
8
+ gem 'factory_girl'
8
9
  end
9
10
 
10
11
  group :development do
data/MIT-LICENSE CHANGED
@@ -1,4 +1,4 @@
1
- Copyright (c) 2010 Rob Halff
1
+ Copyright (c) 2013 Ryan Oblak
2
2
 
3
3
  Permission is hereby granted, free of charge, to any person obtaining
4
4
  a copy of this software and associated documentation files (the
data/README.md CHANGED
@@ -3,35 +3,51 @@ Seed Dump
3
3
 
4
4
  Seed Dump is a Rails 4 plugin that adds a rake task named `db:seed:dump`.
5
5
 
6
- It allows you to create a `db/seeds.rb` from the existing data in your database.
6
+ It allows you to create seed data files from the existing data in your database.
7
+
8
+ You can also use Seed Dump from the Rails console. See below for usage examples.
7
9
 
8
10
  Note: if you want to use Seed Dump with Rails 3 or earlier, use [version 0.5.3](http://rubygems.org/gems/seed_dump/versions/0.5.3).
9
11
 
10
- Example Usage
11
- -------------
12
+ Installation
13
+ ------------
14
+
15
+ Add it to your Gemfile with:
16
+
17
+ gem 'seed_dump'
18
+
19
+ Or install it by hand:
20
+
21
+ $ gem install seed_dump
22
+
23
+ Examples
24
+ --------
25
+
26
+ ### Rake task
12
27
 
13
28
  Dump all data directly to `db/seeds.rb`:
14
29
 
15
30
  $ rake db:seed:dump
16
31
 
17
- Dump only data from the users and products table and dump a maximum amount of 2 records:
32
+ Result:
18
33
 
19
- $ rake db:seed:dump MODELS=User,Product LIMIT=2
34
+ Product.create!([
35
+ {category_id: 1, description: "Long Sleeve Shirt", name: "Long Sleeve Shirt"},
36
+ {category_id: 3, description: "Plain White Tee Shirt", name: "Plain T-Shirt"}
37
+ ])
38
+ User.create!([
39
+ {id: 1, password: "123456", username: "test_1"},
40
+ {id: 2, password: "234567", username: "test_2"}
41
+ ])
20
42
 
21
- Result:
43
+ Dump only data from the users table and dump a maximum amount of 1 record:
22
44
 
23
- $ cat db/seeds.rb
24
- # Autogenerated by the db:seed:dump task
25
- # Do not hesitate to tweak this to your needs
45
+ $ rake db:seed:dump MODELS=User,Product LIMIT=1
26
46
 
27
- products = Product.create!([
28
- { :category_id => 1, :description => "Long Sleeve Shirt", :name => "Long Sleeve Shirt" },
29
- { :category_id => 3, :description => "Plain White Tee Shirt", :name => "Plain T-Shirt" }
30
- ])
47
+ Result:
31
48
 
32
- users = User.create!([
33
- { :id => 1, :password => "123456", :username => "test_1" },
34
- { :id => 2, :password => "234567", :username => "tes2" }
49
+ User.create!([
50
+ {id: 1, password: "123456", username: "test_1"}
35
51
  ])
36
52
 
37
53
  Append to `db/seeds.rb` instead of overwriting it:
@@ -40,42 +56,42 @@ Append to `db/seeds.rb` instead of overwriting it:
40
56
 
41
57
  Use another output file instead of `db/seeds.rb`:
42
58
 
43
- rake db:seed:dump FILE=db/categories.rb
44
-
45
- If you want the dump to use `create` rather than `create!`:
46
-
47
- rake db:seed:dump CREATE_METHOD='create'
59
+ rake db:seed:dump FILE=db/seeds/users.rb
48
60
 
49
- There are more environment variables that can be set— see below for all of them.
61
+ There are more options that can be set— see below for all of them.
50
62
 
63
+ ### Console
51
64
 
52
- Installation
53
- ------------
65
+ Output a dump of all User records:
54
66
 
55
- Add it to your Gemfile with:
67
+ irb(main):001:0> puts SeedDump.dump(User)
68
+ User.create!([
69
+ {id: 1, password: "123456", username: "test_1"},
70
+ {id: 2, password: "234567", username: "test_2"}
71
+ ])
56
72
 
57
- gem 'seed_dump'
73
+ Write the dump to a file:
58
74
 
59
- Or install it by hand:
75
+ irb(main):002:0> SeedDump.dump(User, file: 'db/seeds.rb')
60
76
 
61
- $ gem install seed_dump
77
+ Append the dump to a file:
62
78
 
79
+ irb(main):003:0> puts SeedDump.dump(User, file: 'db/seeds.rb', append: true)
63
80
 
64
- All environment variables
65
- -------------------------
81
+ Options are specified as a Hash to the second argument.
66
82
 
67
- `APPEND`: If set to `true`, append the data to the file instead of overwriting it. Default: `false`.
83
+ Options
84
+ -------
68
85
 
69
- `CREATE_METHOD`: Use the specified create method rather than `create!` (the default).
86
+ Options are common to both the Rake task and the console, except where noted.
70
87
 
71
- `FILE`: Use a different output file. Default: `db/seeds.rb`.
88
+ `append`: If set to `true`, append the data to the file instead of overwriting it. Default: `false`.
72
89
 
73
- `LIMIT`: Dump no more then this amount of data. Default: no limit.
90
+ `exclude`: Attributes to be excluded from the dump. Default: `id, created_at, updated_at`.
74
91
 
75
- `MAX`: Split one create action per model into several create actions with MAX elements in each. Default: no limit. Useful for large data dumping to reduce memory usage.
92
+ `file`: Write to the specified output file. Default in Rake task is `db/seeds.rb`. Console returns the dump as a string by default.
76
93
 
77
- `MODEL[S]`: A model name or a comma-separated list of models. Default: all models.
94
+ `limit`: Dump no more then this amount of data. Default: no limit. Rake task only. In the console just pass in an ActiveRecord::Relation with the appropriate limit (e.g. `SeedDump.dump(User.limit(5))`).
78
95
 
79
- `WITH_ID`: If set to `true`, include the `:id` in the `create` options. Default: `false`.
96
+ `model[s]`: Restrict the dump to the specified comma-separated list of models. Default: all models. Rake task only.
80
97
 
81
- `TIMESTAMPS`: If set to `true`, include the `:created_by` and `:updated_by` timestamps. Default: `true`.
data/Rakefile CHANGED
@@ -10,6 +10,7 @@ begin
10
10
  gem.email = 'rroblak@gmail.com'
11
11
  gem.homepage = 'https://github.com/rroblak/seed_dump'
12
12
  gem.authors = ['Rob Halff', 'Ryan Oblak']
13
+ gem.license = 'MIT'
13
14
  end
14
15
  Jeweler::GemcutterTasks.new
15
16
  rescue LoadError
data/VERSION CHANGED
@@ -1 +1 @@
1
- 2.0.0
1
+ 3.0.0
data/lib/seed_dump.rb CHANGED
@@ -1,7 +1,10 @@
1
+ require 'seed_dump/dump_methods/enumeration'
1
2
  require 'seed_dump/dump_methods'
3
+ require 'seed_dump/environment'
2
4
 
3
5
  class SeedDump
4
- include SeedDump::DumpMethods
6
+ extend Environment
7
+ extend DumpMethods
5
8
 
6
9
  require 'seed_dump/railtie' if defined?(Rails)
7
10
  end
@@ -1,151 +1,96 @@
1
- require "true"
2
- require "clip"
3
-
4
1
  class SeedDump
5
2
  module DumpMethods
3
+ include Enumeration
6
4
 
7
- def initialize
8
- @opts = {}
9
- @ar_options = {}
10
- @indent = ""
11
- @models = []
12
- @seed_rb = ""
13
- @id_set_string = ""
14
- end
5
+ def dump(records, options = {})
6
+ return nil if records.count == 0
15
7
 
16
- def setup(env)
17
- # config
18
- @opts['verbose'] = env["VERBOSE"].true? || env['VERBOSE'].nil?
19
- @opts['debug'] = env["DEBUG"].true?
20
- @opts['with_id'] = env["WITH_ID"].true?
21
- @opts['timestamps'] = env["TIMESTAMPS"].true? || env["TIMESTAMPS"].nil?
22
- @opts['models'] = env['MODELS'] || env['MODEL'] || ""
23
- @opts['file'] = env['FILE'] || "#{Rails.root}/db/seeds.rb"
24
- @opts['append'] = (env['APPEND'].true? && File.exists?(@opts['file']) )
25
- @opts['max'] = env['MAX'] && env['MAX'].to_i > 0 ? env['MAX'].to_i : nil
26
- @indent = " " * (env['INDENT'].nil? ? 2 : env['INDENT'].to_i)
27
- @opts['create_method'] = env['CREATE_METHOD'] || 'create!'
28
-
29
- @limit = (env['LIMIT'].to_i > 0) ? env['LIMIT'].to_i : nil
30
-
31
- @models = @opts['models'].split(',').collect {|x| x.strip.underscore.singularize.camelize.constantize }
32
- end
8
+ io = open_io(options)
33
9
 
34
- def log(msg)
35
- puts msg if @opts['debug']
36
- end
10
+ write_records_to_io(records, io, options)
37
11
 
38
- def models
39
- @models
12
+ ensure
13
+ io.close if io.present?
40
14
  end
41
15
 
42
- def dump_attribute(a_s, r, k, v)
43
- pushed = false
44
- if v.is_a?(BigDecimal)
45
- v = v.to_s
46
- else
47
- v = attribute_for_inspect(r,k)
48
- end
16
+ private
49
17
 
50
- unless k == 'id' && !@opts['with_id']
51
- if (!(k == 'created_at' || k == 'updated_at') || @opts['timestamps'])
52
- a_s.push("#{k.to_sym.inspect} => #{v}")
53
- pushed = true
54
- end
55
- end
56
- pushed
57
- end
18
+ def dump_record(record, options)
19
+ attribute_strings = []
58
20
 
59
- def dump_model(model)
60
- @id_set_string = ''
61
- create_hash = ""
62
- rows = []
21
+ options[:exclude] ||= [:id, :created_at, :updated_at]
63
22
 
23
+ # We select only string attribute names to avoid conflict
24
+ # with the composite_primary_keys gem (it returns composite
25
+ # primary key attribute names as hashes).
26
+ record.attributes.select {|key| key.is_a?(String) }.each do |attribute, value|
27
+ attribute_strings << dump_attribute_new(attribute, value) unless options[:exclude].include?(attribute.to_sym)
28
+ end
64
29
 
65
- model.find_each(batch_size: (@limit || 1000)) do |record|
66
- attr_s = [];
30
+ "{#{attribute_strings.join(", ")}}"
31
+ end
67
32
 
68
- record.attributes.select {|x| x.is_a?(String) }.each do |k,v|
69
- dump_attribute(attr_s, record, k, v)
70
- end
33
+ def dump_attribute_new(attribute, value)
34
+ "#{attribute}: #{value_to_s(value)}"
35
+ end
71
36
 
72
- rows.push "#{@indent}{ " << attr_s.join(', ') << " }"
37
+ def value_to_s(value)
38
+ value = case value
39
+ when BigDecimal
40
+ value.to_s
41
+ when Date, Time, DateTime
42
+ value.to_s(:db)
43
+ else
44
+ value
45
+ end
46
+
47
+ value.inspect
48
+ end
73
49
 
74
- break if rows.length == @limit
75
- end
50
+ def open_io(options)
51
+ if options[:file].present?
52
+ mode = options[:append] ? 'a+' : 'w+'
76
53
 
77
- if @opts['max']
78
- splited_rows = rows.each_slice(@opts['max']).to_a
79
- maxsarr = []
80
- splited_rows.each do |sr|
81
- maxsarr << "\n#{model}.#{@opts['create_method']}([\n" << sr.join(",\n") << "\n])\n"
82
- end
83
- maxsarr.join('')
54
+ File.open(options[:file], mode)
84
55
  else
85
- "\n#{model}.#{@opts['create_method']}([\n" << rows.join(",\n") << "\n])\n"
56
+ StringIO.new('', 'w+')
86
57
  end
87
-
88
58
  end
89
59
 
90
- def dump_models
91
- if @models.empty?
92
- Rails.application.eager_load!
60
+ def write_records_to_io(records, io, options)
61
+ io.write("#{model_for(records)}.create!([\n ")
93
62
 
94
- @seed_rb = ""
63
+ enumeration_method = if records.is_a?(ActiveRecord::Relation) || records.is_a?(Class)
64
+ :active_record_enumeration
65
+ else
66
+ :enumerable_enumeration
67
+ end
95
68
 
96
- @models = ActiveRecord::Base.descendants.select do |model|
97
- (model.to_s != 'ActiveRecord::SchemaMigration') && \
98
- model.table_exists? && \
99
- model.exists?
100
- end
101
- end
102
-
103
- @models.sort! { |a, b| a.to_s <=> b.to_s }
69
+ send(enumeration_method, records, io, options) do |record_strings, last_batch|
70
+ io.write(record_strings.join(",\n "))
104
71
 
105
- @models.each do |model|
106
- puts "Adding #{model} seeds." if @opts['verbose']
107
-
108
- @seed_rb << dump_model(model) << "\n\n"
72
+ io.write(",\n ") unless last_batch
109
73
  end
110
74
 
111
- @seed_rb
112
- end
113
-
114
- def write_file
115
- File.open(@opts['file'], (@opts['append'] ? "a" : "w")) { |f|
116
- f << "# encoding: utf-8\n"
117
- f << "# Autogenerated by the db:seed:dump task\n# Do not hesitate to tweak this to your needs\n" unless @opts['append']
118
- f << "#{@seed_rb}"
119
- }
120
- end
121
-
122
- #override the rails version of this function to NOT truncate strings
123
- def attribute_for_inspect(r,k)
124
- value = r.attributes[k]
75
+ io.write("\n])\n")
125
76
 
126
- if value.is_a?(String) && value.length > 50
127
- "#{value}".inspect
128
- elsif value.is_a?(Date) || value.is_a?(Time)
129
- %("#{value.to_s(:db)}")
77
+ if options[:file].present?
78
+ nil
130
79
  else
131
- value.inspect
80
+ io.rewind
81
+ io.read
132
82
  end
133
83
  end
134
84
 
135
- def output
136
- @seed_rb
85
+ def model_for(records)
86
+ if records.is_a?(Class)
87
+ records
88
+ elsif records.respond_to?(:model)
89
+ records.model
90
+ else
91
+ records[0].class
92
+ end
137
93
  end
138
94
 
139
- def run(env)
140
- setup env
141
-
142
- puts "Appending seeds to #{@opts['file']}." if @opts['append']
143
- dump_models
144
-
145
- puts "Writing #{@opts['file']}."
146
- write_file
147
-
148
- puts "Done."
149
- end
150
95
  end
151
96
  end
@@ -0,0 +1,73 @@
1
+ class SeedDump
2
+ module DumpMethods
3
+ module Enumeration
4
+ def active_record_enumeration(records, io, options)
5
+ # If the records don't already have an order,
6
+ # order them by primary key ascending.
7
+ if !records.respond_to?(:arel) || records.arel.orders.blank?
8
+ records.order("#{records.quoted_table_name}.#{records.quoted_primary_key} ASC")
9
+ end
10
+
11
+ num_of_batches, batch_size, last_batch_size = batch_params_from(records, options)
12
+
13
+ # Loop through each batch
14
+ (1..num_of_batches).each do |batch_number|
15
+
16
+ record_strings = []
17
+
18
+ last_batch = (batch_number == num_of_batches)
19
+
20
+ cur_batch_size = if last_batch
21
+ last_batch_size
22
+ else
23
+ batch_size
24
+ end
25
+
26
+ # Loop through the records of the current batch
27
+ records.offset((num_of_batches - 1) * batch_size).limit(cur_batch_size).each do |record|
28
+ record_strings << dump_record(record, options)
29
+ end
30
+
31
+ yield record_strings, last_batch
32
+ end
33
+ end
34
+
35
+ def enumerable_enumeration(records, io, options)
36
+ num_of_batches, batch_size = batch_params_from(records, options)
37
+
38
+ record_strings = []
39
+
40
+ batch_number = 1
41
+
42
+ records.each_with_index do |record, i|
43
+ record_strings << dump_record(record, options)
44
+
45
+ last_batch = (i == records.length - 1)
46
+
47
+ if (record_strings.length == batch_size) || last_batch
48
+ yield record_strings, last_batch
49
+
50
+ record_strings = []
51
+ batch_number += 1
52
+ end
53
+ end
54
+ end
55
+
56
+ def batch_params_from(records, options)
57
+ batch_size = batch_size_from(records, options)
58
+
59
+ count = records.count
60
+
61
+ [((count / batch_size) + 1), batch_size, (count % batch_size)]
62
+ end
63
+
64
+ def batch_size_from(records, options)
65
+ if options[:batch_size].present?
66
+ options[:batch_size].to_i
67
+ else
68
+ 1000
69
+ end
70
+ end
71
+ end
72
+ end
73
+ end
@@ -0,0 +1,33 @@
1
+ class SeedDump
2
+ module Environment
3
+
4
+ def dump_using_environment(env = {})
5
+ Rails.application.eager_load!
6
+
7
+ models = if env['MODEL'] || env['MODELS']
8
+ (env['MODEL'] || env['MODELS']).split(',').collect {|x| x.strip.underscore.singularize.camelize.constantize }
9
+ else
10
+ ActiveRecord::Base.descendants.select do |model|
11
+ (model.to_s != 'ActiveRecord::SchemaMigration') && \
12
+ model.table_exists? && \
13
+ model.exists?
14
+ end
15
+ end
16
+
17
+ append = (env['APPEND'] == 'true')
18
+
19
+ models.each do |model|
20
+ model = model.limit(env['LIMIT'].to_i) if env['LIMIT']
21
+
22
+ SeedDump.dump(model,
23
+ append: append,
24
+ batch_size: (env['BATCH_SIZE'] ? env['BATCH_SIZE'].to_i : nil),
25
+ exclude: (env['EXCLUDE'] ? env['EXCLUDE'].split(',').map {|e| e.strip.to_sym} : nil),
26
+ file: (env['FILE'] || 'db/seeds.rb'))
27
+
28
+ append = true
29
+ end
30
+ end
31
+ end
32
+ end
33
+
@@ -3,7 +3,7 @@ namespace :db do
3
3
  desc "Dump records from the database into db/seeds.rb"
4
4
  task :dump => :environment do
5
5
 
6
- SeedDump.new.run(ENV)
6
+ SeedDump.dump_using_environment(ENV)
7
7
 
8
8
  end
9
9
  end
data/seed_dump.gemspec CHANGED
@@ -5,11 +5,11 @@
5
5
 
6
6
  Gem::Specification.new do |s|
7
7
  s.name = "seed_dump"
8
- s.version = "2.0.0"
8
+ s.version = "3.0.0"
9
9
 
10
10
  s.required_rubygems_version = Gem::Requirement.new(">= 0") if s.respond_to? :required_rubygems_version=
11
11
  s.authors = ["Rob Halff", "Ryan Oblak"]
12
- s.date = "2013-10-16"
12
+ s.date = "2013-12-07"
13
13
  s.description = "Dump (parts) of your database to db/seeds.rb to get a headstart creating a meaningful seeds.rb file"
14
14
  s.email = "rroblak@gmail.com"
15
15
  s.extra_rdoc_files = [
@@ -17,24 +17,28 @@ Gem::Specification.new do |s|
17
17
  ]
18
18
  s.files = [
19
19
  ".rspec",
20
- "CHANGELOG.rdoc",
21
20
  "Gemfile",
22
21
  "MIT-LICENSE",
23
22
  "README.md",
24
23
  "Rakefile",
25
24
  "VERSION",
26
- "lib/clip.rb",
27
25
  "lib/seed_dump.rb",
28
26
  "lib/seed_dump/dump_methods.rb",
27
+ "lib/seed_dump/dump_methods/enumeration.rb",
28
+ "lib/seed_dump/environment.rb",
29
29
  "lib/seed_dump/railtie.rb",
30
30
  "lib/tasks/seed_dump.rake",
31
- "lib/true.rb",
32
31
  "seed_dump.gemspec",
32
+ "spec/dump_methods_spec.rb",
33
+ "spec/environment_spec.rb",
34
+ "spec/factories/another_samples.rb",
35
+ "spec/factories/samples.rb",
36
+ "spec/factories/yet_another_samples.rb",
33
37
  "spec/helpers.rb",
34
- "spec/seed_dump_spec.rb",
35
38
  "spec/spec_helper.rb"
36
39
  ]
37
40
  s.homepage = "https://github.com/rroblak/seed_dump"
41
+ s.licenses = ["MIT"]
38
42
  s.require_paths = ["lib"]
39
43
  s.rubygems_version = "2.0.3"
40
44
  s.summary = "{Seed Dumper for Rails}"
@@ -46,17 +50,20 @@ Gem::Specification.new do |s|
46
50
  s.add_runtime_dependency(%q<activesupport>, [">= 0"])
47
51
  s.add_runtime_dependency(%q<activerecord>, [">= 0"])
48
52
  s.add_development_dependency(%q<byebug>, [">= 0"])
53
+ s.add_development_dependency(%q<factory_girl>, [">= 0"])
49
54
  s.add_development_dependency(%q<jeweler>, [">= 0"])
50
55
  else
51
56
  s.add_dependency(%q<activesupport>, [">= 0"])
52
57
  s.add_dependency(%q<activerecord>, [">= 0"])
53
58
  s.add_dependency(%q<byebug>, [">= 0"])
59
+ s.add_dependency(%q<factory_girl>, [">= 0"])
54
60
  s.add_dependency(%q<jeweler>, [">= 0"])
55
61
  end
56
62
  else
57
63
  s.add_dependency(%q<activesupport>, [">= 0"])
58
64
  s.add_dependency(%q<activerecord>, [">= 0"])
59
65
  s.add_dependency(%q<byebug>, [">= 0"])
66
+ s.add_dependency(%q<factory_girl>, [">= 0"])
60
67
  s.add_dependency(%q<jeweler>, [">= 0"])
61
68
  end
62
69
  end
@@ -0,0 +1,111 @@
1
+ require 'spec_helper'
2
+
3
+ describe SeedDump do
4
+
5
+ describe '.dump' do
6
+ before do
7
+ Rails.application.eager_load!
8
+
9
+ create_db
10
+
11
+ 3.times { FactoryGirl.create(:sample) }
12
+
13
+ @expected_output = "Sample.create!([\n {string: \"string\", text: \"text\", integer: 42, float: 3.14, decimal: \"2.72\", datetime: \"1776-07-04 19:14:00\", time: \"2000-01-01 03:15:00\", date: \"1863-11-19\", binary: \"binary\", boolean: false},\n {string: \"string\", text: \"text\", integer: 42, float: 3.14, decimal: \"2.72\", datetime: \"1776-07-04 19:14:00\", time: \"2000-01-01 03:15:00\", date: \"1863-11-19\", binary: \"binary\", boolean: false},\n {string: \"string\", text: \"text\", integer: 42, float: 3.14, decimal: \"2.72\", datetime: \"1776-07-04 19:14:00\", time: \"2000-01-01 03:15:00\", date: \"1863-11-19\", binary: \"binary\", boolean: false}\n])\n"
14
+ end
15
+
16
+ context 'without file option' do
17
+ it 'should return the dump of the models passed in' do
18
+ SeedDump.dump(Sample).should eq(@expected_output)
19
+ end
20
+ end
21
+
22
+ context 'with file option' do
23
+ before do
24
+ @filename = Dir::Tmpname.make_tmpname(File.join(Dir.tmpdir, 'foo'), nil)
25
+ end
26
+
27
+ after do
28
+ File.unlink(@filename)
29
+ end
30
+
31
+ it 'should dump the models to the specified file' do
32
+ SeedDump.dump(Sample, file: @filename)
33
+
34
+ File.open(@filename) { |file| file.read.should eq(@expected_output) }
35
+ end
36
+
37
+ context 'with append option' do
38
+ it 'should append to the file rather than overwriting it' do
39
+ SeedDump.dump(Sample, file: @filename)
40
+ SeedDump.dump(Sample, file: @filename, append: true)
41
+
42
+ File.open(@filename) { |file| file.read.should eq(@expected_output + @expected_output) }
43
+ end
44
+ end
45
+ end
46
+
47
+ context 'ActiveRecord relation' do
48
+ it 'should return nil if the count is 0' do
49
+ SeedDump.dump(EmptyModel).should be(nil)
50
+ end
51
+
52
+ context 'with an order parameter' do
53
+ it 'should dump the models in the specified order' do
54
+ Sample.delete_all
55
+ samples = 3.times {|i| FactoryGirl.create(:sample, integer: i) }
56
+
57
+ SeedDump.dump(Sample.order('integer DESC')).should eq("Sample.create!([\n {string: \"string\", text: \"text\", integer: 2, float: 3.14, decimal: \"2.72\", datetime: \"1776-07-04 19:14:00\", time: \"2000-01-01 03:15:00\", date: \"1863-11-19\", binary: \"binary\", boolean: false},\n {string: \"string\", text: \"text\", integer: 1, float: 3.14, decimal: \"2.72\", datetime: \"1776-07-04 19:14:00\", time: \"2000-01-01 03:15:00\", date: \"1863-11-19\", binary: \"binary\", boolean: false},\n {string: \"string\", text: \"text\", integer: 0, float: 3.14, decimal: \"2.72\", datetime: \"1776-07-04 19:14:00\", time: \"2000-01-01 03:15:00\", date: \"1863-11-19\", binary: \"binary\", boolean: false}\n])\n")
58
+ end
59
+ end
60
+
61
+ context 'without an order parameter' do
62
+ it 'should dump the models sorted by primary key ascending' do
63
+ Sample.delete_all
64
+ samples = 3.times {|i| FactoryGirl.create(:sample, integer: i) }
65
+
66
+ SeedDump.dump(Sample).should eq("Sample.create!([\n {string: \"string\", text: \"text\", integer: 0, float: 3.14, decimal: \"2.72\", datetime: \"1776-07-04 19:14:00\", time: \"2000-01-01 03:15:00\", date: \"1863-11-19\", binary: \"binary\", boolean: false},\n {string: \"string\", text: \"text\", integer: 1, float: 3.14, decimal: \"2.72\", datetime: \"1776-07-04 19:14:00\", time: \"2000-01-01 03:15:00\", date: \"1863-11-19\", binary: \"binary\", boolean: false},\n {string: \"string\", text: \"text\", integer: 2, float: 3.14, decimal: \"2.72\", datetime: \"1776-07-04 19:14:00\", time: \"2000-01-01 03:15:00\", date: \"1863-11-19\", binary: \"binary\", boolean: false}\n])\n")
67
+ end
68
+ end
69
+
70
+ context 'with a limit parameter' do
71
+ it 'should dump the number of models specified by the limit when the limit is smaller than the batch size' do
72
+ expected_output = "Sample.create!([\n {string: \"string\", text: \"text\", integer: 42, float: 3.14, decimal: \"2.72\", datetime: \"1776-07-04 19:14:00\", time: \"2000-01-01 03:15:00\", date: \"1863-11-19\", binary: \"binary\", boolean: false}\n])\n"
73
+
74
+ SeedDump.dump(Sample.limit(1)).should eq(expected_output)
75
+ end
76
+
77
+ it 'should dump the number of models specified by the limit when the limit is larger than the batch size but not a multiple of the batch size' do
78
+ Sample.delete_all
79
+ 4.times { FactoryGirl.create(:sample) }
80
+
81
+ SeedDump.dump(Sample.limit(3), batch_size: 2).should eq(@expected_output)
82
+ end
83
+ end
84
+ end
85
+
86
+ context 'with a batch_size parameter' do
87
+ it 'should not raise an exception' do
88
+
89
+ SeedDump.dump(Sample, batch_size: 100)
90
+ end
91
+ end
92
+
93
+ context 'Array' do
94
+ it 'should return the dump of the models passed in' do
95
+ SeedDump.dump(Sample.all.to_a, batch_size: 2).should eq(@expected_output)
96
+ end
97
+
98
+ it 'should return nil if the array is empty' do
99
+ SeedDump.dump([]).should be(nil)
100
+ end
101
+ end
102
+
103
+ context 'with an exclude parameter' do
104
+ it 'should exclude the specified attributes from the dump' do
105
+ expected_output = "Sample.create!([\n {text: \"text\", integer: 42, decimal: \"2.72\", time: \"2000-01-01 03:15:00\", date: \"1863-11-19\", binary: \"binary\", boolean: false},\n {text: \"text\", integer: 42, decimal: \"2.72\", time: \"2000-01-01 03:15:00\", date: \"1863-11-19\", binary: \"binary\", boolean: false},\n {text: \"text\", integer: 42, decimal: \"2.72\", time: \"2000-01-01 03:15:00\", date: \"1863-11-19\", binary: \"binary\", boolean: false}\n])\n"
106
+
107
+ SeedDump.dump(Sample, exclude: [:id, :created_at, :updated_at, :string, :float, :datetime]).should eq(expected_output)
108
+ end
109
+ end
110
+ end
111
+ end
@@ -0,0 +1,136 @@
1
+ require 'spec_helper'
2
+
3
+ describe SeedDump do
4
+ describe '.dump_using_environment' do
5
+ before(:all) do
6
+ create_db
7
+ end
8
+
9
+ before(:each) do
10
+ Rails.application.eager_load!
11
+
12
+ FactoryGirl.create(:sample)
13
+ end
14
+
15
+ describe 'APPEND' do
16
+ it "should specify append as true if the APPEND env var is 'true'" do
17
+ SeedDump.should_receive(:dump).with(anything, include(append: true))
18
+
19
+ SeedDump.dump_using_environment('APPEND' => 'true')
20
+ end
21
+
22
+ it "should specify append as false the first time if the APPEND env var is not 'true' (and true after that)" do
23
+ FactoryGirl.create(:another_sample)
24
+
25
+ SeedDump.should_receive(:dump).with(anything, include(append: false)).ordered
26
+ SeedDump.should_receive(:dump).with(anything, include(append: true)).ordered
27
+
28
+ SeedDump.dump_using_environment('APPEND' => 'false')
29
+ end
30
+ end
31
+
32
+ describe 'BATCH_SIZE' do
33
+ it 'should pass along the specified batch size' do
34
+ SeedDump.should_receive(:dump).with(anything, include(batch_size: 17))
35
+
36
+ SeedDump.dump_using_environment('BATCH_SIZE' => '17')
37
+ end
38
+
39
+ it 'should pass along a nil batch size if BATCH_SIZE is not specified' do
40
+ SeedDump.should_receive(:dump).with(anything, include(batch_size: nil))
41
+
42
+ SeedDump.dump_using_environment
43
+ end
44
+ end
45
+
46
+ describe 'EXCLUDE' do
47
+ it 'should pass along any attributes to be excluded' do
48
+ SeedDump.should_receive(:dump).with(anything, include(exclude: [:baggins, :saggins]))
49
+
50
+ SeedDump.dump_using_environment('EXCLUDE' => 'baggins,saggins')
51
+ end
52
+ end
53
+
54
+ describe 'FILE' do
55
+ it 'should pass the FILE parameter to the dump method correctly' do
56
+ SeedDump.should_receive(:dump).with(anything, include(file: 'blargle'))
57
+
58
+ SeedDump.dump_using_environment('FILE' => 'blargle')
59
+ end
60
+
61
+ it 'should pass db/seeds.rb as the file parameter if no FILE is specified' do
62
+ SeedDump.should_receive(:dump).with(anything, include(file: 'db/seeds.rb'))
63
+
64
+ SeedDump.dump_using_environment
65
+ end
66
+ end
67
+
68
+ describe 'LIMIT' do
69
+ it 'should apply the specified limit to the records' do
70
+ relation_double = double('ActiveRecord relation double')
71
+ Sample.should_receive(:limit).with(5).and_return(relation_double)
72
+
73
+ SeedDump.should_receive(:dump).with(relation_double, anything)
74
+ SeedDump.stub(:dump)
75
+
76
+ SeedDump.dump_using_environment('LIMIT' => '5')
77
+ end
78
+ end
79
+
80
+ describe 'MODEL' do
81
+ it 'if MODEL is not specified it should dump all non-empty models' do
82
+ FactoryGirl.create(:another_sample)
83
+
84
+ [Sample, AnotherSample].each do |model|
85
+ SeedDump.should_receive(:dump).with(model, anything)
86
+ end
87
+
88
+ SeedDump.dump_using_environment
89
+ end
90
+
91
+ it 'if MODEL is specified it should only dump the specified model' do
92
+ FactoryGirl.create(:another_sample)
93
+
94
+ SeedDump.should_receive(:dump).with(Sample, anything)
95
+
96
+ SeedDump.dump_using_environment('MODEL' => 'Sample')
97
+ end
98
+ end
99
+
100
+ describe 'MODELS' do
101
+ it 'if MODELS is not specified it should dump all non-empty models' do
102
+ FactoryGirl.create(:another_sample)
103
+
104
+ [Sample, AnotherSample].each do |model|
105
+ SeedDump.should_receive(:dump).with(model, anything)
106
+ end
107
+
108
+ SeedDump.dump_using_environment
109
+ end
110
+
111
+ it 'if MODELS is specified it should only dump those models' do
112
+ FactoryGirl.create(:another_sample)
113
+ FactoryGirl.create(:yet_another_sample)
114
+
115
+ SeedDump.should_receive(:dump).with(Sample, anything)
116
+ SeedDump.should_receive(:dump).with(AnotherSample, anything)
117
+
118
+ SeedDump.dump_using_environment('MODELS' => 'Sample, AnotherSample')
119
+ end
120
+ end
121
+
122
+ it 'should run ok without ActiveRecord::SchemaMigration being set (needed for Rails Engines)' do
123
+ schema_migration = ActiveRecord::SchemaMigration
124
+
125
+ ActiveRecord.send(:remove_const, :SchemaMigration)
126
+
127
+ SeedDump.stub(:dump)
128
+
129
+ begin
130
+ SeedDump.dump_using_environment
131
+ ensure
132
+ ActiveRecord.const_set(:SchemaMigration, schema_migration)
133
+ end
134
+ end
135
+ end
136
+ end
@@ -0,0 +1,14 @@
1
+ FactoryGirl.define do
2
+ factory :another_sample do
3
+ string 'string'
4
+ text 'text'
5
+ integer 42
6
+ float 3.14
7
+ decimal 2.72
8
+ datetime DateTime.parse('July 4, 1776 7:14pm UTC')
9
+ time Time.parse('3:15am UTC')
10
+ date Date.parse('November 19, 1863')
11
+ binary 'binary'
12
+ boolean false
13
+ end
14
+ end
@@ -0,0 +1,14 @@
1
+ FactoryGirl.define do
2
+ factory :sample do
3
+ string 'string'
4
+ text 'text'
5
+ integer 42
6
+ float 3.14
7
+ decimal 2.72
8
+ datetime DateTime.parse('July 4, 1776 7:14pm UTC')
9
+ time Time.parse('3:15am UTC')
10
+ date Date.parse('November 19, 1863')
11
+ binary 'binary'
12
+ boolean false
13
+ end
14
+ end
@@ -0,0 +1,14 @@
1
+ FactoryGirl.define do
2
+ factory :yet_another_sample do
3
+ string 'string'
4
+ text 'text'
5
+ integer 42
6
+ float 3.14
7
+ decimal 2.72
8
+ datetime DateTime.parse('July 4, 1776 7:14pm UTC')
9
+ time Time.parse('3:15am UTC')
10
+ date Date.parse('November 19, 1863')
11
+ binary 'binary'
12
+ boolean false
13
+ end
14
+ end
data/spec/helpers.rb CHANGED
@@ -11,16 +11,12 @@ class Rails
11
11
  if !@already_called
12
12
  Object.const_set('Sample', Class.new(ActiveRecord::Base))
13
13
 
14
- Object.const_set('AbstractSample', Class.new(ActiveRecord::Base))
15
- AbstractSample.abstract_class = true
14
+ Object.const_set('AnotherSample', Class.new(ActiveRecord::Base))
16
15
 
17
- Object.const_set('ChildSample', Class.new(AbstractSample))
16
+ Object.const_set('YetAnotherSample', Class.new(ActiveRecord::Base))
18
17
 
19
18
  Object.const_set('NoTableModel', Class.new(ActiveRecord::Base))
20
19
 
21
- Object.const_set('Nested', Module.new)
22
- Nested.const_set('Sample', Class.new(ActiveRecord::Base))
23
-
24
20
  Object.const_set('EmptyModel', Class.new(ActiveRecord::Base))
25
21
 
26
22
  @already_called = true
@@ -33,20 +29,43 @@ module Helpers
33
29
  ActiveRecord::Migration.verbose = false
34
30
 
35
31
  ActiveRecord::Schema.define(:version => 1) do
36
- create_table 'child_samples', :force => true do |t|
37
- t.string 'name'
32
+ create_table 'samples', :force => true do |t|
33
+ t.string 'string'
34
+ t.text 'text'
35
+ t.integer 'integer'
36
+ t.float 'float'
37
+ t.decimal 'decimal'
38
+ t.datetime 'datetime'
39
+ t.time 'time'
40
+ t.date 'date'
41
+ t.binary 'binary'
42
+ t.boolean 'boolean'
38
43
  t.datetime 'created_at', :null => false
39
44
  t.datetime 'updated_at', :null => false
40
45
  end
41
46
 
42
- create_table 'samples', :force => true do |t|
47
+ create_table 'another_samples', :force => true do |t|
48
+ t.string 'string'
49
+ t.text 'text'
50
+ t.integer 'integer'
51
+ t.float 'float'
52
+ t.decimal 'decimal'
53
+ t.datetime 'datetime'
54
+ t.time 'time'
55
+ t.date 'date'
56
+ t.binary 'binary'
57
+ t.boolean 'boolean'
58
+ t.datetime 'created_at', :null => false
59
+ t.datetime 'updated_at', :null => false
60
+ end
61
+
62
+ create_table 'yet_another_samples', :force => true do |t|
43
63
  t.string 'string'
44
64
  t.text 'text'
45
65
  t.integer 'integer'
46
66
  t.float 'float'
47
67
  t.decimal 'decimal'
48
68
  t.datetime 'datetime'
49
- t.datetime 'timestamp'
50
69
  t.time 'time'
51
70
  t.date 'date'
52
71
  t.binary 'binary'
data/spec/spec_helper.rb CHANGED
@@ -1,13 +1,19 @@
1
1
  require 'seed_dump'
2
- require 'active_support/core_ext/string'
3
- require 'active_support/descendants_tracker'
2
+
3
+ require 'active_support'
4
4
  require 'active_record'
5
+
5
6
  require 'byebug'
7
+
6
8
  require 'database_cleaner'
9
+ require 'factory_girl'
10
+
7
11
  require './spec/helpers'
8
12
 
9
13
  ActiveRecord::Base.establish_connection(:adapter => 'sqlite3', :database => ':memory:')
10
14
 
15
+ FactoryGirl.find_definitions
16
+
11
17
  RSpec.configure do |config|
12
18
  config.treat_symbols_as_metadata_keys_with_true_values = true
13
19
 
metadata CHANGED
@@ -1,7 +1,7 @@
1
1
  --- !ruby/object:Gem::Specification
2
2
  name: seed_dump
3
3
  version: !ruby/object:Gem::Version
4
- version: 2.0.0
4
+ version: 3.0.0
5
5
  platform: ruby
6
6
  authors:
7
7
  - Rob Halff
@@ -9,7 +9,7 @@ authors:
9
9
  autorequire:
10
10
  bindir: bin
11
11
  cert_chain: []
12
- date: 2013-10-16 00:00:00.000000000 Z
12
+ date: 2013-12-07 00:00:00.000000000 Z
13
13
  dependencies:
14
14
  - !ruby/object:Gem::Dependency
15
15
  name: activesupport
@@ -53,6 +53,20 @@ dependencies:
53
53
  - - '>='
54
54
  - !ruby/object:Gem::Version
55
55
  version: '0'
56
+ - !ruby/object:Gem::Dependency
57
+ name: factory_girl
58
+ requirement: !ruby/object:Gem::Requirement
59
+ requirements:
60
+ - - '>='
61
+ - !ruby/object:Gem::Version
62
+ version: '0'
63
+ type: :development
64
+ prerelease: false
65
+ version_requirements: !ruby/object:Gem::Requirement
66
+ requirements:
67
+ - - '>='
68
+ - !ruby/object:Gem::Version
69
+ version: '0'
56
70
  - !ruby/object:Gem::Dependency
57
71
  name: jeweler
58
72
  requirement: !ruby/object:Gem::Requirement
@@ -76,24 +90,28 @@ extra_rdoc_files:
76
90
  - README.md
77
91
  files:
78
92
  - .rspec
79
- - CHANGELOG.rdoc
80
93
  - Gemfile
81
94
  - MIT-LICENSE
82
95
  - README.md
83
96
  - Rakefile
84
97
  - VERSION
85
- - lib/clip.rb
86
98
  - lib/seed_dump.rb
87
99
  - lib/seed_dump/dump_methods.rb
100
+ - lib/seed_dump/dump_methods/enumeration.rb
101
+ - lib/seed_dump/environment.rb
88
102
  - lib/seed_dump/railtie.rb
89
103
  - lib/tasks/seed_dump.rake
90
- - lib/true.rb
91
104
  - seed_dump.gemspec
105
+ - spec/dump_methods_spec.rb
106
+ - spec/environment_spec.rb
107
+ - spec/factories/another_samples.rb
108
+ - spec/factories/samples.rb
109
+ - spec/factories/yet_another_samples.rb
92
110
  - spec/helpers.rb
93
- - spec/seed_dump_spec.rb
94
111
  - spec/spec_helper.rb
95
112
  homepage: https://github.com/rroblak/seed_dump
96
- licenses: []
113
+ licenses:
114
+ - MIT
97
115
  metadata: {}
98
116
  post_install_message:
99
117
  rdoc_options: []
data/CHANGELOG.rdoc DELETED
@@ -1,56 +0,0 @@
1
- == Seed Dump
2
-
3
- == 0.4.3 / 2013-05-11
4
-
5
- * Handle abstract_class setting in ActiveRecord [craigjackson]
6
- * added MAX option [OlegPasko]
7
-
8
- == 0.4.2 / 2012-11-02
9
-
10
- * Fix for bug resulting from top-level class redefinition [rroblak]
11
-
12
- == 0.4.1 / 2012-08-01
13
-
14
- * include TIMESTAMPS by default
15
- * add TIMESTAMP flag and checks against attr_accessible [limratana].
16
- * modifications for better testing
17
- * make MODEL_DIR actually work
18
-
19
- == 0.4.0 / 2012-07-28
20
-
21
- * fix rdoc issue.
22
- * automatically use :without_protection if created_at, updated_at are present.
23
- * Properly dump decimal columns
24
- * support nested models [h6y3]
25
- * add WITHOUT_PROTECTION flag [Alexey Yurchenko]
26
- * add utf-8 encoding comment [Alexey Yurchenko, Alexey Poimtsev, n0b0dy]
27
- * add SKIP_CALLBACKS flag [Alexey Yurchenko]
28
- * fixed typo in README [Andrey Ognevsky]
29
- * add PG_SCHEMA flag [Luka Novsak]
30
-
31
- == 0.3.4 / 2011-07-14
32
-
33
- * Skip models that aren't Derived from ActiveRecord [iconoclast]
34
- * override the AR version of attribute_for_inspect to NOT truncate strings [sc0ttman]
35
-
36
- == 0.3.3 / 2011-07-14
37
-
38
- * solve sorting issue
39
-
40
- == 0.3.2 / 2011-04-22
41
-
42
- * fix broken APPEND option
43
-
44
- == 0.3.1 / 2011-04-22
45
-
46
- * use different syntax for multiple rows
47
-
48
- == 0.3.0 / 2011-04-22
49
-
50
- * refactor to make testing possible
51
-
52
- == 0.2.4 / 2011-04-22
53
-
54
- * properly quote any value (also fixes Time value generation)
55
- * solve issue when specifying WITH_ID [David Guthu]
56
-
data/lib/clip.rb DELETED
@@ -1,6 +0,0 @@
1
- # by digitalross: http://stackoverflow.com/questions/1604305/all-but-last-element-of-ruby-array
2
- class Array
3
- def clip n=1
4
- take size - n
5
- end
6
- end
data/lib/true.rb DELETED
@@ -1,9 +0,0 @@
1
- # http://veerasundaravel.wordpress.com/2010/10/26/string-to-boolean-conversion-in-ruby/
2
- class Object
3
- def true? # to boolean
4
- return false if self.nil?
5
- return true if self == true || self =~ (/(true|t|yes|y|1)$/i)
6
- return false if self == false || self.nil? || self =~ (/(false|f|no|n|0)$/i)
7
- raise ArgumentError.new('invalid value for Boolean: "#{self}"')
8
- end
9
- end
@@ -1,157 +0,0 @@
1
- require 'spec_helper'
2
-
3
- describe SeedDump do
4
- describe '#dump_models' do
5
- before(:all) do
6
- create_db
7
- end
8
-
9
- before(:each) do
10
- @sd = SeedDump.new
11
-
12
- @env = {'FILE' => Dir.pwd + '/spec/db/seeds.rb',
13
- 'VERBOSE' => false,
14
- 'DEBUG' => false}
15
-
16
- ActiveSupport::DescendantsTracker.clear
17
- end
18
-
19
- it 'should not include timestamps if the TIMESTAMPS parameter is false' do
20
- Rails.application.eager_load!
21
-
22
- @env['MODELS'] = 'Sample'
23
- @env['TIMESTAMPS'] = false
24
-
25
- @sd.setup @env
26
-
27
- load_sample_data
28
-
29
- @sd.dump_models.should match(/^\nSample\.create!\(\[\n { :string => nil, :text => nil, :integer => nil, :float => nil, :decimal => nil, :datetime => nil, :timestamp => nil, :time => nil, :date => nil, :binary => nil, :boolean => nil }\n\]\)\n\n\n$/)
30
- end
31
-
32
- it 'should include timestamps if the TIMESTAMPS parameter is true' do
33
- Rails.application.eager_load!
34
-
35
- @env['MODELS'] = 'Sample'
36
- @env['TIMESTAMPS'] = true
37
-
38
- load_sample_data
39
-
40
- @sd.setup @env
41
-
42
- @sd.dump_models.should match(/^\nSample\.create!\(\[\n { :string => nil, :text => nil, :integer => nil, :float => nil, :decimal => nil, :datetime => nil, :timestamp => nil, :time => nil, :date => nil, :binary => nil, :boolean => nil, :created_at => "\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}", :updated_at => "\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}" }\n\]\)\n\n\n$/)
43
- end
44
-
45
- it 'should include ids if the WITH_ID parameter is true' do
46
- Rails.application.eager_load!
47
-
48
- @env['MODELS'] = 'Sample'
49
- @env['WITH_ID'] = true
50
-
51
- @sd.setup @env
52
-
53
- load_sample_data
54
-
55
- @sd.dump_models.should match(/^\nSample\.create!\(\[\n { :id => \d+, :string => nil, :text => nil, :integer => nil, :float => nil, :decimal => nil, :datetime => nil, :timestamp => nil, :time => nil, :date => nil, :binary => nil, :boolean => nil, :created_at => "\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}", :updated_at => "\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}" }\n\]\)\n\n\n$/)
56
- end
57
-
58
- it 'should respect the MODELS parameter' do
59
- Rails.application.eager_load!
60
-
61
- @env['MODELS'] = 'Sample'
62
-
63
- @sd.setup @env
64
-
65
- load_sample_data
66
-
67
- @sd.dump_models.should match(/\nSample\.create!\(\[\n { :string => nil, :text => nil, :integer => nil, :float => nil, :decimal => nil, :datetime => nil, :timestamp => nil, :time => nil, :date => nil, :binary => nil, :boolean => nil, :created_at => "\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}", :updated_at => "\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}" }\n\]\)\n\n\n/)
68
- end
69
-
70
- it 'should use the create method specified in the CREATE_METHOD parameter' do
71
- load_sample_data
72
-
73
- @env['MODELS'] = 'Sample'
74
- @env['CREATE_METHOD'] = 'create'
75
-
76
- @sd.setup @env
77
-
78
- @sd.dump_models.should match(/\nSample\.create\(\[\n { :string => nil, :text => nil, :integer => nil, :float => nil, :decimal => nil, :datetime => nil, :timestamp => nil, :time => nil, :date => nil, :binary => nil, :boolean => nil, :created_at => "\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}", :updated_at => "\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}" }\n\]\)\n\n\n/)
79
- end
80
-
81
- it "should use 'create!' as the default create method" do
82
- load_sample_data
83
-
84
- @env['MODELS'] = 'Sample'
85
-
86
- @sd.setup @env
87
-
88
- @sd.dump_models.should match(/\nSample\.create!\(\[\n { :string => nil, :text => nil, :integer => nil, :float => nil, :decimal => nil, :datetime => nil, :timestamp => nil, :time => nil, :date => nil, :binary => nil, :boolean => nil, :created_at => "\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}", :updated_at => "\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}" }\n\]\)\n\n\n/)
89
- end
90
-
91
- it "should return the contents of the dump" do
92
- load_sample_data
93
-
94
- @env['MODELS'] = 'Sample'
95
-
96
- @sd.setup @env
97
-
98
- @sd.dump_models.should match(/\nSample\.create!\(\[\n { :string => nil, :text => nil, :integer => nil, :float => nil, :decimal => nil, :datetime => nil, :timestamp => nil, :time => nil, :date => nil, :binary => nil, :boolean => nil, :created_at => "\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}", :updated_at => "\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}" }\n\]\)\n\n\n/)
99
- end
100
-
101
- it 'should run ok without ActiveRecord::SchemaMigration being set (needed for Rails Engines)' do
102
- schema_migration = ActiveRecord::SchemaMigration
103
-
104
- ActiveRecord.send(:remove_const, :SchemaMigration)
105
-
106
- begin
107
- @sd.setup @env
108
-
109
- @sd.dump_models
110
- ensure
111
- ActiveRecord.const_set(:SchemaMigration, schema_migration)
112
- end
113
- end
114
-
115
- it "should skip any models whose tables don't exist" do
116
- @sd.setup @env
117
-
118
- load_sample_data
119
-
120
- @sd.dump_models.should match(/\nSample\.create!\(\[\n { :string => nil, :text => nil, :integer => nil, :float => nil, :decimal => nil, :datetime => nil, :timestamp => nil, :time => nil, :date => nil, :binary => nil, :boolean => nil, :created_at => "\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}", :updated_at => "\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}" }\n\]\)\n\n\n/)
121
- end
122
-
123
- it "should skip any models that don't have have any rows" do
124
- @sd.setup @env
125
-
126
- @sd.dump_models.should_not include('EmptyModel')
127
- end
128
-
129
- it 'should respect the LIMIT parameter' do
130
- load_sample_data
131
- load_sample_data
132
-
133
- @env['MODELS'] = 'Sample'
134
- @env['LIMIT'] = '1'
135
-
136
- @sd.setup @env
137
-
138
- @sd.dump_models.should match(/\nSample\.create!\(\[\n { :string => nil, :text => nil, :integer => nil, :float => nil, :decimal => nil, :datetime => nil, :timestamp => nil, :time => nil, :date => nil, :binary => nil, :boolean => nil, :created_at => "\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}", :updated_at => "\d{4}-\d{2}-\d{2} \d{2}:\d{2}:\d{2}" }\n\]\)\n\n\n/)
139
- end
140
-
141
- it 'should only pull attributes that are returned as strings' do
142
- load_sample_data
143
-
144
- @env['MODELS'] = 'Sample'
145
- @env['LIMIT'] = '1'
146
-
147
- @sd.setup @env
148
-
149
- original_attributes = Sample.new.attributes
150
- attributes = original_attributes.merge(['col1', 'col2', 'col3'] => 'ABC')
151
-
152
- Sample.any_instance.stub(:attributes).and_return(attributes)
153
-
154
- @sd.dump_models.should eq("\nSample.create!([\n { :string => nil, :text => nil, :integer => nil, :float => nil, :decimal => nil, :datetime => nil, :timestamp => nil, :time => nil, :date => nil, :binary => nil, :boolean => nil, :created_at => nil, :updated_at => nil }\n])\n\n\n")
155
- end
156
- end
157
- end