From ba4c789e82b6da0078c39d211b155e5a64e0a604 Mon Sep 17 00:00:00 2001 From: Miguel Nogueira Date: Mon, 20 May 2024 00:57:45 +0100 Subject: [PATCH] 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 --- main.rb | 24 +++++++++++++----------- 1 file changed, 13 insertions(+), 11 deletions(-) diff --git a/main.rb b/main.rb index ef0487a..fb9a91b 100644 --- a/main.rb +++ b/main.rb @@ -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,8 +108,9 @@ 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] client_errors[ip] += 1 @@ -117,18 +118,19 @@ lines.each do |line| client_errors[ip] = 1 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