-
Notifications
You must be signed in to change notification settings - Fork 0
/
transformer.rb
68 lines (53 loc) · 1.86 KB
/
transformer.rb
1
2
3
4
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
64
65
66
67
68
module SimpleCsv
class Transformer < Base
DEFAULT_FILENAME = 'converted.csv'
def initialize(path, **opts, &block)
@transforms = {}
@output_headers = []
@caller_self = eval 'self', block.binding
if settings.for_csv[:headers]
@csv_path = File.expand_path path
headers(*find_headers) unless headers.any?
end
instance_exec(self, &block)
apply_transforms path, **opts
end
def output_headers(*out_headers)
return @output_headers if @output_headers.any?
@output_headers = out_headers.map(&:to_s)
alias_to_friendly_headers @output_headers
@output_headers
end
private
def apply_transforms(path, **opts)
received_headers = headers
timestamp = Time.new.strftime '%d-%m-%Y-%S%7N'
output_path = opts.delete(:output) || "#{path.split('.')[0..-2].join}-#{timestamp}.csv"
output_headers = @output_headers.any? ? @output_headers : received_headers
SimpleCsv.read path, opts do |reader|
SimpleCsv.generate output_path, opts do |writer|
writer.headers *output_headers
reader.each_row do
output_headers.each do |column|
transform = find_transform column
result = transform ? transform.call(reader.send(column))
: reader.send(column)
writer.send column, result
end
end
end
end
end
def find_transform(column)
@transforms[(@col_map.key(column.to_s) || column).to_sym]
end
def method_missing(mtd, *args, &block)
mstr = mtd.to_s
if headers.include?(mstr) || @output_headers.include?(mstr) || @col_map.key?(mstr)
@transforms[mtd] = block || args.first unless @transforms.key? mtd
else
@caller_self.send mtd, *args, &block
end
end
end
end