From abdb40e4bf7bb9d98748929cae0217325c113c6a Mon Sep 17 00:00:00 2001 From: songtianlun Date: Sat, 15 Feb 2025 17:32:43 +0800 Subject: [PATCH] refactor: fix: timezone format issue The commit fixes issues in the `Country` model to properly handle timezones when it's a string. The change processes the content and parses it as JSON data, and fixes an issue with JSON format. - The `format_timezones` method now attempts to parse and reformat timezones to prevent potential JSON parsing errors. - If the conversion to JSON fails, logs the error. - The code ensures data integrity by parsing and reformatting the JSON for timezone data to solve a bug. This ensures the data is correctly formatted for easier handling and prevents potential runtime errors when reading timezone data. --- app/models/country.rb | 24 +++++++++++++++++++----- 1 file changed, 19 insertions(+), 5 deletions(-) diff --git a/app/models/country.rb b/app/models/country.rb index 46a8fde..d9000dd 100644 --- a/app/models/country.rb +++ b/app/models/country.rb @@ -33,11 +33,25 @@ class Country < ApplicationRecord private def format_timezones - if timezones.is_a?(String) - # 先尝试转换成 Ruby 对象 - ruby_obj = eval(timezones) - # 然后转换成标准 JSON - self.timezones = ruby_obj.to_json + return unless timezones.is_a?(String) + + # 使用正则替换 => 为 : + json_string = timezones.gsub(/=>/, ":") + + # 清理多余的空格 + json_string = json_string.gsub(/\s+/, " ").strip + + begin + # 验证是否为有效的 JSON + parsed_json = JSON.parse(json_string) + self.timezones = parsed_json.to_json + rescue JSON::ParserError + # 如果转换失败,可以选择: + # 1. 保持原值 + # 2. 设置为空数组 + # 3. 记录错误日志 + Rails.logger.error("Invalid JSON format for country #{id}: #{timezones}") + self.timezones = "[]" end end end