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. </commit_message> </commit_message> </commit_message> This ensures the data is correctly formatted for easier handling and prevents potential runtime errors when reading timezone data. </commit_message>
This commit is contained in:
parent
eb9bfc7972
commit
abdb40e4bf
@ -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
|
||||
|
Loading…
Reference in New Issue
Block a user