710db7a3c89633c1cc7afbd28839de91b3ecdd59
[quanlib.git] / classify / classset.rb
1 require 'csv'
2
3 require 'bookclass'
4
5 class ClassSet
6   @@class_csv_file = 'class.csv'
7
8   def initialize
9     @entries = {}
10     load!(@@class_csv_file)
11   end
12
13   def add!(info)
14     key = construct_key(info.grouping, info.title)
15     @entries[key] = info
16   end
17
18   def construct_key(author_grouping, title)
19     author_grouping.to_s + '|' + title.to_s
20   end
21
22   def get(author_grouping, title)
23     key = construct_key(author_grouping, title)
24     if @entries.has_key?(key)
25       return @entries[key]
26     else
27       return nil
28     end
29   end
30
31   def has_key?(author_grouping, title)
32     @entries.has_key?(construct_key(author_grouping, title))
33   end
34
35   def ensure_contains!(info)
36     if ! has_key?(info.grouping, info.title)
37       add!(info)
38     end
39   end
40
41   def inspect 
42     data = []
43
44     if nil != @entries 
45       data.push('entries=' + @entries.inspect + '') 
46     end
47
48     return '(ClassSet:' + data.join(',') + ')'
49   end
50
51   def load!(file_name)
52     first = true
53     @entries = {}
54
55     if ! File.exist?(file_name)
56       puts 'WARNING:  file "' + file_name + '" not found.'
57       return 
58     end
59
60     File.open(file_name, 'r:UTF-8') do |fd|
61       csv = CSV.new(fd)
62       csv.to_a.each do |row|
63         if first
64           first = false
65         elsif row.length >= 6
66           ddc = row[0]
67           lcc = row[1]
68           grouping = row[2]
69           author = row[3]
70           title = row[4]
71           fast = []
72           if nil != row[5]
73             fast = row[5].split(';')
74           end
75   
76           bookclass = BookClass.new(grouping, title)
77           bookclass.ddc = ddc
78           bookclass.lcc = lcc
79           bookclass.author = author
80   
81           fast.each do |id|
82             bookclass.add_fast(id)
83           end
84   
85           key = construct_key(grouping, title)
86           @entries[key] = bookclass
87         end
88       end
89     end
90   end
91
92   def save(file_name)
93     CSV.open(file_name, 'w:UTF-8') do |csv|
94       csv << ['Dewey', 'LCC', 'Grouping', 'Author', 'Title', 'FAST']
95
96       @entries.keys.sort.each do |key|
97         info = @entries[key]
98
99         ddc = info.ddc
100         lcc = info.lcc
101         grouping = info.grouping
102         author = info.author
103         title = info.title
104         fast_list = info.fast
105         fast_ids = []
106         fast_list.each do |tuple|
107           fast_ids.push(tuple[0])
108         end
109         fast = fast_ids.join(';')
110         
111         csv << [ ddc, lcc, grouping, author, title, fast ]
112       end
113     end
114   end
115
116   def save_state
117     save(@@class_csv_file)
118   end
119 end
120