5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
|
# File 'lib/sower.rb', line 5
def self.seed(clazz, filename, options = {})
sql_path = File.join(seeds_path, "#{filename}.sql")
csv_path = File.join(seeds_path, "#{filename}.csv")
text_path = File.join(seeds_path, "#{filename}.txt")
old_table_name = clazz.table_name
if @schema.present?
clazz.table_name = "#{@schema}.#{clazz.table_name}"
end
if clazz.respond_to?(:enumeration_model_updates_permitted=)
clazz.enumeration_model_updates_permitted = true
end
if File.exists?(sql_path)
puts "Importing #{filename} to #{clazz.table_name} as SQL"
data = File.read(sql_path)
ActiveRecord::Base.connection.execute data
elsif File.exists?(csv_path)
puts "Importing #{filename} to #{clazz.table_name} as CSV"
index = 0
CSV.foreach(csv_path) do |row|
attributes = {}
unless columns = options[:columns]
columns = [:name, :description]
end
columns.each_with_index do |col, i|
if value = row[i]
attributes[col] = value.try(:strip)
end
end
m = clazz.new(attributes)
m.id = index
m.save(:validate => false)
index += 1
end
else
puts "Importing #{filename} to #{clazz.table_name} as Text"
File.foreach(text_path).each_with_index do |line, index|
m = clazz.new(:name => line.chomp)
m.id = index
m.save(:validate => false)
end
end
if clazz.count > 1
ActiveRecord::Base.connection.execute \
"SELECT setval('#{clazz.table_name}_id_seq'::regclass, MAX(id)) FROM #{clazz.table_name};"
end
clazz.table_name = old_table_name
end
|