Created
April 4, 2014 11:25
-
-
Save lldong/9972635 to your computer and use it in GitHub Desktop.
Convert NSDictionary/NSArray to literal syntax
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
#!/usr/bin/env ruby | |
# encoding: utf-8 | |
require 'strscan' | |
def construct_dict_literal(pairs, mutable = false) | |
output = pairs.each_slice(2).reduce('@{') { | |
|expr, pair| | |
value, key = *pair | |
expr << key.strip << ': ' | |
expr << value.strip << ', ' | |
}[0...-2] << '}' | |
mutable ? "[#{output} mutableCopy]" : output | |
end | |
def construct_array_literal(list, mutable = false) | |
output = list.reduce('@[') { |expr, item| | |
expr << item.strip << ', ' | |
}[0...-2] << ']' | |
mutable ? "[#{output} mutableCopy]" : output | |
end | |
expr = ARGV.join('') | |
expr = expr.force_encoding("UTF-8") | |
expr = expr.gsub(/\n/, '').gsub(/\s+/, ' ') | |
class Scanner < StringScanner | |
def dictionary? | |
scan(/\[\s*NSDictionary\s+dictionaryWithObjectsAndKeys:/) || | |
scan(/\[\s*\[NSDictionary\s+alloc\]\s+initWithObjectsAndKeys:/) | |
end | |
def mutable_dictionary? | |
scan(/\[\s*NSMutableDictionary\s+dictionaryWithObjectsAndKeys:/) || | |
scan(/\[\s*\[NSMutableDictionary\s+alloc\]\s+initWithObjectsAndKeys:/) | |
end | |
def array? | |
scan(/\[\s*NSArray\s+arrayWithObjects:/) || | |
scan(/\[\s*\[NSArray\s+alloc\]\s+initWithObjects:/) | |
end | |
def mutable_array? | |
scan(/\[\s*NSMutableArray\s+arrayWithObjects:/) || | |
scan(/\[\s*\[NSMutableArray\s+alloc\]\s+initWithObjects:/) | |
end | |
end | |
scanner = Scanner.new(expr) | |
scanner.skip(/\s+/) | |
if scanner.dictionary? | |
pairs = scanner.scan_until(/nil/).split(',')[0...-1] | |
puts construct_dict_literal(pairs).force_encoding("UTF-8") | |
elsif scanner.mutable_dictionary? | |
pairs = scanner.scan_until(/nil/).split(',')[0...-1] | |
puts construct_dict_literal(pairs, true).force_encoding("UTF-8") | |
elsif scanner.array? | |
items = scanner.scan_until(/nil/).split(',')[0...-1] | |
puts construct_array_literal(items).force_encoding("UTF-8") | |
elsif scanner.mutable_array? | |
items = scanner.scan_until(/nil/).split(',')[0...-1] | |
puts construct_array_literal(items, true).force_encoding("UTF-8") | |
else | |
puts ":(" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment