-
Notifications
You must be signed in to change notification settings - Fork 0
/
init.rb
86 lines (74 loc) · 1.71 KB
/
init.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
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
$: << File.dirname(__FILE__)
require 'parser/json_parser'
require 'parser/ini_parser'
require 'user'
require 'post'
class Task
def self.validate_file!(file_name)
file_path = File.join(File.dirname(__FILE__), file_name)
if !File.exists? file_path
raise "File not found!"
end
end
def self.init_with_file_name(file_name)
file_path = File.join(File.dirname(__FILE__), file_name)
new(file_name)
end
def initialize(file_path)
@file_path = file_path
end
def get_parser_by_name(file_path)
file_extension = File.extname(file_path)
parser = nil
case file_extension
when ".json"
parser = Parser::JSONParser.new
when ".ini"
parser = Parser::IniParser.new
else
end
parser
end
def get_model_by_name(file_path)
model = nil
if file_path =~ /user/i
model = User
elsif file_path =~ /post/i
model = Post
end
model
end
def run!
parser = get_parser_by_name(@file_path)
if !parser.nil?
model = get_model_by_name(@file_path)
if model.nil?
raise "Model not found!"
end
data = load_and_parse(@file_path, parser)
if data.nil?
raise "Data cannot be parsed!"
end
create_model_by_list(model, data)
else
raise "Parser not found!"
end
end
def create_model_by_list(model, data)
thread = []
mutex = Mutex.new
data.each do |item|
thread << Thread.new(item) { |item_for_create|
mutex.synchronize do
user = model.new(item_for_create)
user.save
end
}
sleep 0.3
end
thread.each(&:join)
end
def load_and_parse(file_path, parser)
parser.parse_from_file(file_path)
end
end