· 8 years ago · Jun 15, 2018, 05:36 PM
1require 'fastercsv'
2require 'optparse'
3require 'find'
4
5namespace :db do desc "Insert or Update the database with fresh data"
6 task :ccn => [:environment] do |t, args|
7 @cols = []
8 @colh = {}
9 @recchk = {}
10 @dep = ''
11 @div = ''
12 @cnm = ''
13 @ccn = ''
14 @objt = Kernel.const_get( "CostCenter".to_sym )
15
16 cmpcol = File.new("/home/cjay/crap/costcenters.col", "r")
17 cmpimp = File.new("/home/cjay/crap/costcenters", "r")
18
19 # Assemble the columns
20 #
21 while(@line = cmpcol.gets)
22 @cols << @line.chomp
23 @colh[@line.chomp] = (@cols.length - 1)
24 end
25
26 # Gather the id number for each active row
27 #
28 @objt.find_each(:select => "id") do |@dep|
29 @recchk[@dep.id] = false
30 end
31
32 # Iterate through everything and sort through updates
33 #
34 while @line = cmpimp.gets
35 @line = @line.chomp
36 @line = @line.split(/\t/)
37 @cnm = ''
38 @div = ''
39 @dep = ''
40
41 if(@line.length != @cols.length)
42 print "Error: Line and Col element count does not match\n"
43 end
44
45 # If the record exists, then update the columns and save it
46 #
47 # Find the parent
48 #
49 @cnm = CompanyNumber .first(:conditions => {:number => @line[ @colh["number"] ]})
50 @div = @cnm.divisions .first(:conditions => {:div => @line[ @colh["div"] ]})
51 @dep = @div.departments .first(:conditions => {:dep => @line[ @colh["dep"] ]})
52 @ccn = @dep.cost_centers .first(:conditions => {:ccn => @line[ @colh["ccn"] ]})
53
54 if( @ccn )
55 @recchk[@ccn.id] = true
56 @ccn.description = @line[ @colh["description"] ]
57 @ccn.save
58
59 # Otherwise, create a new copy of the record
60 #
61 else
62 @ccn = @div.cost_centers.build( :ccn => @line[ @colh["ccn"] ],
63 :description => @line[ @colh["description"] ])
64 @dep.save
65 end
66 end
67
68 # Delete rows that can't be found
69 #
70 @recchk.each do |key, value|
71 if value == true
72 next
73 end
74
75 print "key not found in table: #{key}\n"
76
77
78 @objt.destroy(key)
79 end
80 end
81end