Skip to content

Commit 4609f66

Browse files
committed
Add word list cache invalidation mechanism to refresh the word list after 30 days
1 parent 6269b61 commit 4609f66

File tree

1 file changed

+26
-3
lines changed

1 file changed

+26
-3
lines changed

lib/moderate/word_list.rb

+26-3
Original file line numberDiff line numberDiff line change
@@ -8,17 +8,24 @@
88
module Moderate
99
class WordList
1010
WORD_LIST_URL = 'https://raw.githubusercontent.com/coffee-and-fun/google-profanity-words/main/data/en.txt'
11+
CACHE_TTL = 30 * 24 * 60 * 60 # 30 days in seconds
1112

1213
class << self
1314
def load
1415
cache_path = cache_file_path
1516

1617
begin
1718
if File.exist?(cache_path)
18-
words = File.read(cache_path, encoding: 'UTF-8').split("\n").to_set
19-
return words unless words.empty?
19+
if cache_valid?(cache_path)
20+
words = File.read(cache_path, encoding: 'UTF-8').split("\n").to_set
21+
return words unless words.empty?
22+
else
23+
logger.info("[moderate gem] Cache expired (older than #{CACHE_TTL / 86400} days). Refreshing word list...")
24+
return download_and_cache(cache_path)
25+
end
2026
end
2127

28+
logger.info("[moderate gem] No cache found. Downloading word list for the first time...")
2229
download_and_cache(cache_path)
2330
rescue StandardError => e
2431
logger.error("[moderate gem] Error loading word list: #{e.message}")
@@ -27,8 +34,22 @@ def load
2734
end
2835
end
2936

37+
def refresh_word_list!
38+
logger.info("[moderate gem] Manually refreshing word list")
39+
cache_path = cache_file_path
40+
File.delete(cache_path) if File.exist?(cache_path)
41+
download_and_cache(cache_path)
42+
end
43+
3044
private
3145

46+
def cache_valid?(cache_path)
47+
return false unless File.exist?(cache_path)
48+
49+
cache_age = Time.now - File.mtime(cache_path)
50+
cache_age <= CACHE_TTL
51+
end
52+
3253
def cache_file_path
3354
if defined?(Rails)
3455
Rails.root.join('tmp', 'moderate_bad_words.txt')
@@ -52,7 +73,9 @@ def download_and_cache(cache_path)
5273
raise Moderate::Error, "Downloaded word list is empty"
5374
end
5475

55-
logger.info("[moderate gem] Downloaded #{words.size} words from #{WORD_LIST_URL}")
76+
logger.info("[moderate gem] Successfully downloaded and cached #{words.size} words to #{cache_path}")
77+
logger.info("[moderate gem] Next cache refresh will occur after: #{Time.now + CACHE_TTL}")
78+
5679
File.write(cache_path, content, encoding: 'UTF-8')
5780
logger.debug("[moderate gem] Cached word list to: #{cache_path}")
5881

0 commit comments

Comments
 (0)