refactor: lightly refactored code for easier reading

This commit refactored some of the variables so they're easier to read

Signed-off-by: Miguel Nogueira <me@nogueira.codes>
This commit is contained in:
Miguel Nogueira 2024-05-20 00:57:45 +01:00
parent 61d5d26329
commit ba4c789e82
Signed by: miguel456
GPG Key ID: 43EF15DB0CC86DDD
1 changed files with 13 additions and 11 deletions

20
main.rb
View File

@ -56,7 +56,7 @@ def get_line_code(line)
end
# Gets the user agent of the given log line
def get_line_ua(line)
def get_line_browser(line)
pattern = /"([^"]*)"$/
user_agent = line.match(pattern)[0] if line.match(pattern)
@ -89,7 +89,7 @@ end
visit_counter = {}
client_errors = {}
user_agents = {}
browsers = {}
all_ips = []
lines.each do |line|
@ -108,7 +108,8 @@ end
lines.each do |line|
ip = get_line_ip(line).to_s
code = get_line_code(line)
ua = get_line_ua(line)
browser = get_line_browser(line)
# refactored from "ua" to "browser"
if is_client_err?(code.to_i)
if client_errors[ip]
@ -118,17 +119,18 @@ lines.each do |line|
end
end
if user_agents[ua]
user_agents[ua] += 1
# refactored from: "user_agents[ua]" to "browsers[browser]"
if browsers[browser]
browsers[browser] += 1
else
user_agents[ua] = 1
browsers[browser] = 1
end
end
top_user_agents = user_agents.sort_by { |_ua, count| -count }.first(5)
puts 'Top 5 User-Agents contacting the site:'
top_user_agents.each do |ua, count|
top_browsers = browsers.sort_by { |_ua, count| -count }.first(5)
puts 'Top 5 browsers contacting the site:'
top_browsers.each do |ua, count|
puts "#{ua}: #{count} visits"
end