Skip to content

Instantly share code, notes, and snippets.

@fizvlad
Created August 9, 2020 16:06
Show Gist options
  • Save fizvlad/e177b94ae476da40b4af727ce39289af to your computer and use it in GitHub Desktop.
Save fizvlad/e177b94ae476da40b4af727ce39289af to your computer and use it in GitHub Desktop.
Does **most** of the work when migrating from JSON.mapping to JSON::Serializable
file_data = File.read(ARGV[0])
mapping_regex = /^[ ]+?JSON\.mapping\(\{?$\n(^.+?,?$\n)+?\s+\}?\)/m
file_data.gsub!(mapping_regex) do |match|
result = ''
lines = match.split("\n")
lines.each.with_index do |line, i|
if i.zero?
result << line.sub(/JSON\.mapping\(\{?/, 'include JSON::Serializable') + "\n\n"
elsif i == lines.size - 1
# Do not paste line
else
line.rstrip!
line.delete_prefix!(' ') # Remove intendation
line.delete_suffix!(',')
line.sub!(/^(\s+)(\w+):\s+(.+)/) do
intendation = $1
name = $2
data = $3
if data.start_with?('{')
field_data = data.dup
field_data.delete_prefix!('{')
field_data.delete_suffix!('}')
type = nil
field_data.sub!(/(?:, )?type: ([^,]+)(?:, )?/) do |match|
type = $1
if match.start_with?(', ') && match.end_with?(', ')
', '
else
''
end
end
data_line = field_data.empty? ? '' : "#{intendation}@[JSON::Field(#{field_data})]\n"
property_line = "#{intendation}property #{name} : #{type}"
data_line + property_line
else
"#{intendation}property #{name} : #{data}"
end
end
result << line + (i == lines.size - 2 ? "" : "\n")
end
end
result
end
File.write(ARGV[0], file_data)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment