Skip to content

Instantly share code, notes, and snippets.

@db42
Created July 1, 2016 10:41
Show Gist options
  • Save db42/e8744a8e27c45af3c293d9bf31e2f5f8 to your computer and use it in GitHub Desktop.
Save db42/e8744a8e27c45af3c293d9bf31e2f5f8 to your computer and use it in GitHub Desktop.
Create swift extension implementing Argo(Decodable) for JSONModel classes
def parse_properties_txt(fn)
start = false
properties = {}
model = nil
File.read(fn).lines.each do |l|
if l.start_with?("@interface") && l.include?("JSONModel")
model = l.split[1].tr(":","")
start = true
next
end
next if !start
break if l.start_with?("@end")
next if !l.start_with?("@property")
next if l.include?("Ignore") || l.include?("readonly")
l = l.tr(";", "")
words = l.split
ws = words[-2].split(/<|>|\*/)
property = words[-1].tr("*;\n", "")
propertyType = ws[0]
if propertyType == "NSArray"
type = ws[1]
propertyType = "[#{type}]"
elsif propertyType == "NSString"
propertyType = "String"
elsif propertyType == "int"
propertyType = "Int32"
elsif propertyType == "BOOL"
propertyType = "Bool"
elsif propertyType == "double"
propertyType = "Double"
end
if l.include?("Optional")
propertyType += "?"
end
properties[property] = propertyType
end
return if !model || properties.empty?
puts model
puts properties
parameter = ""
properties.each do |property, type|
parameter += "(#{property}: #{type})"
end
string = "extension #{model}: Decodable {\n"
string += " static func create#{parameter} -> #{model} {\n"
string += " let cl = #{model}()\n"
properties.each do |property, value|
string += " cl.#{property} = #{property}\n"
end
string += " return cl\n"
string += " }\n\n"
string += " public static func decode(j: JSON) -> Decoded<#{model}> {\n"
string += " let c = curry(#{model}.create)\n"
string += " return c\n"
properties.each_with_index do |(property, type), index|
symbol1 = index == 0 ? "<^>" : "<*>"
symbol2 = symbol(type.include?("?"), type.include?("["))
string += " #{symbol1} j #{symbol2} \"#{property}\"\n"
end
string += " }\n"
string += "}\n"
string
end
namespace :strings do
task :convert do
open("Swift+JSONModel.swift", 'w') do |f|
f << "import Foundation\n"
Dir[File.join('.', '*.h')].each do |fn|
properties = parse_properties_txt(fn)
f << properties
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment