class CsvSeeder::CSVSeeder
Public Class Methods
new(folder_path, orders)
click to toggle source
# File lib/csv_seeder.rb, line 17 def initialize(folder_path, orders) @folder_path = folder_path @orders = orders @dirs = Dir.glob(folder_path + "/*").shuffle end
Public Instance Methods
dir_to_plural(dir)
click to toggle source
# File lib/csv_seeder.rb, line 64 def dir_to_plural(dir) /db\/seeds\/(\w*)\.csv/ =~ dir return $1 end
dirs_loop!()
click to toggle source
# File lib/csv_seeder.rb, line 23 def dirs_loop! while !@dirs.empty? if invalid_order? postpone! next end if has_relations? postpone! next end /db\/seeds\/(\w*)\.csv/ =~ @dirs[0] model = $1.classify CSV.foreach(@dirs[0], headers: true) do |row| Object.const_get(model).create!(**row.to_hash) rescue => e p "Error! During #{model}" p e end p "#{model} saved!" @dirs.shift end end
has_relations?()
click to toggle source
# File lib/csv_seeder.rb, line 55 def has_relations? CSV.open(@dirs[0], &:readline).any? do |header| id_list = @dirs.map do |dir| dir_to_plural(dir).singularize + '_id' end id_list.include? header end end
invalid_order?()
click to toggle source
# File lib/csv_seeder.rb, line 46 def invalid_order? @orders.each do |order| index = order.index(dir_to_plural(@dirs[0]).to_sym) next if !index || index == 0 return true if @dirs.any?{|dir| order[0..(index-1)].map(&:to_s).include? dir_to_plural(dir)} end false end
postpone!()
click to toggle source
# File lib/csv_seeder.rb, line 69 def postpone! @dirs.push @dirs.shift end