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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
|
# File 'lib/imexport.rb', line 2
def self.import(file_name, options = {})
model = Kernel.const_get(options[:class_name].to_s.classify)
find_method = "find_by_#{options[:find_by]}"
columns_prefix = options[:db_columns_prefix].to_s
scan_regexp = Regexp.new("^\\s*#{columns_prefix}(\\w+)\\: (.*)")
attr_map = options[:map] || {}
IO.foreach(file_name) do |line|
unless (line =~ /^\*+ \d+\. row \*+$/).nil?
unless block_given?
if !@model.nil? and @model.valid?
if (s = model.send("#{find_method}", @model.title))
s.update_attributes(@model.attributes.reject{|k,v| v.nil?})
else
@model.save
end
else
$stderr.puts "\n>>> ERRORS while storing #{options[:class_name]}: #{@model.errors.full_messages.join('; ')}\n#{@model.inspect}" unless @model.nil?
end
else
yield(@model)
end
@model = model.new
@last_column_name = nil
@last_column_content = nil
next
end
line.chomp!
column = line.scan(scan_regexp)
unless column.size > 0
@last_column_content << '<br/>' << line
next
end
column.flatten!
@last_column_name = column.first
@last_column_content = column[1].gsub(/\t+/, " ").strip.gsub(/^\n+$/, "").gsub(/\n+/, "<br/>")
if attr_map.include?(@last_column_name)
mattr = attr_map[@last_column_name]
case
when mattr.kind_of?(Symbol)
@model.send("#{mattr.to_s}=", @last_column_content)
when mattr.kind_of?(Proc)
mattr.call(@last_column_content, @model)
when mattr.kind_of?(Hash)
@model.send("#{mattr.keys.first}=", mattr.values.first.call(@last_column_content))
else
$stderr.puts "WARNING: don't know how to handle #{mattr.inspect}"
end
elsif @model.respond_to?(@last_column_name.to_sym)
@model.send("#{@last_column_name}=", @last_column_content)
else
$stderr.puts "WARNING: don't know how to set :#{@last_column_name}"
end
end end
|