-
Notifications
You must be signed in to change notification settings - Fork 7
/
update.rb
56 lines (50 loc) · 1.24 KB
/
update.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
require 'json'
require 'date'
require 'http'
require './db'
def get_translation(word)
resp = HTTP.post(
'https://translation.googleapis.com/language/translate/v2',
json: {
q: word,
source: 'en',
target: 'zh-tw',
format: 'text'
},
params: {
key: ENV["TRANSLATE_API_KEY"]
}
)
data = JSON.parse(resp.to_s)
begin
data["data"]["translations"].first["translatedText"]
rescue => e
puts e
puts data
end
end
translations = DB[:translations]
words = DB[:words]
words.all.each do |word|
zhtw_word = get_translation(word[:english_word])
last_entry = translations
.where(english_word: word[:english_word])
.reverse_order(:last_seen_at)
.order_append(Sequel.desc(:id))
.first
if last_entry.nil? or (last_entry[:zhtw_word] != zhtw_word)
puts "inserting new entry for #{word[:english_word]} -> #{zhtw_word}"
translations.insert(
english_word: word[:english_word],
zhtw_word: zhtw_word,
first_seen_at: DateTime.now,
last_seen_at: DateTime.now
)
else
puts "updating last seen for #{word[:english_word]} -> #{zhtw_word}"
puts last_entry
translations.where(id: last_entry[:id]).update({
last_seen_at: DateTime.now
})
end
end