C0 code coverage information generated on Wed Mar 15 10:52:01 MST 2006
Marked code looks like this.
This line is also marked as covered.
Lines considered as run by rcov, but not reported by Ruby, look like this.
Finally, here's a line marked as not executed.
1 # vim:ts=2:sw=2:sts=2:et
2
3 require 'rubygems'
4 require_gem 'fastercsv'
5
6 class PSVParse
7 attr_reader :headers
8
9 def initialize(file)
10 @file = file
11 @records = FasterCSV.read(@file, {:col_sep => '|'})
12
13 # the headers provide indices for the search method below.
14 # we can make this even more useful by including different
15 # headers maps to correspond to each kind of PSV file.
16
17 @headers = []
18 @records.shift.each do |field|
19 @headers.push field.downcase.to_sym
20 end
21
22 end
23
24 # this is just a handler for the proc generated in the
25 # search method below
26 def lookup(search_term, search_field, &search_proc)
27 yield search_term, search_field
28 end
29
30 #
31 # the search method takes a hash of parameters with the following
32 # values:
33 # :search_term (the string you're searching for)
34 # :result_field (the field your returning values from)
35 # :search_field (the field your searching against)
36 # :negated (optional, boolean - are you doing a negative search)
37 #
38 # the parameter :result_field has a special value, :all
39 # setting :result_field to :all will cause the method to
40 # return an array of arrays containing all the fields for
41 # each matching record.
42 #
43 def search(params)
44 search_term = params[:search_term]
45 search_field = params[:search_field]
46 result_field = params[:result_field]
47 negated = params[:negated] || false
48
49 # build the right kind of search proc
50 if negated == true # am I doing a negative search?
51 if search_term.class == Regexp
52 search_proc = lambda { |search_term, search_field|
53 search_field !~ search_term
54 }
55 else
56 search_proc = lambda { |search_term, search_field|
57 search_field != search_term
58 }
59 end
60 else
61 search_proc = lambda { |search_term, search_field|
62 # the order is inverted to allow === to automagically
63 # check regexps when needed.
64 search_term === search_field
65 }
66 end
67
68
69 results = []
70 if index = @headers.index(search_field)
71 @records.each do |record|
72 if lookup(search_term, record[index], &search_proc)
73
74 # grab the index for the field we're reporting on
75 if result_field == :all
76 result = Hash.new
77 record.each_with_index do |element, num|
78 result[@headers[num]] = element
79 end
80 results << result
81 else
82 results << record[@headers.index(result_field)]
83 end
84 end
85 end
86
87 else
88 # if the field we're searching for doesn't exist,
89 # throw an exception
90 raise ArgumentError, "No such field to search in: #{search_field}"
91 end
92
93 return results unless results.empty?; nil
94
95 end
96
97
98 end

