Class: TypeStruct::Generator
Overview
Respects:
http://json2struct.mervine.net/
https://mholt.github.io/json-to-go/
Instance Method Summary collapse
-
#initialize ⇒ Generator
constructor
A new instance of Generator.
-
#parse(name, h) ⇒ Object
call-seq: parse(name, hash) -> String.
- #parse_one(io, key, value) ⇒ Object
Constructor Details
#initialize ⇒ Generator
Returns a new instance of Generator.
6 7 8 |
# File 'lib/type_struct/generator.rb', line 6 def initialize @io = StringIO.new end |
Instance Method Details
#parse(name, h) ⇒ Object
call-seq:
parse(name, hash) -> String
Auto Generate TypeStruct definition from Hash object.
require ‘type_struct/generator’
puts TypeStruct::Generator.new.parse(“AutoGeneratedStruct”, ‘world!’) # => “AutoGeneratedStruct = TypeStruct.new(\nhello: String,\n)\n”
See also type_struct/generator/json,yaml.rb
21 22 23 24 25 26 27 28 29 30 |
# File 'lib/type_struct/generator.rb', line 21 def parse(name, h) io = StringIO.new io.puts "#{name} = TypeStruct.new(" h.each do |key, value| io.puts " #{key}: #{parse_one(io, key, value)}," end io.puts ")" @io.print io.string @io.string end |
#parse_one(io, key, value) ⇒ Object
32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 |
# File 'lib/type_struct/generator.rb', line 32 def parse_one(io, key, value) case value when Array if value.empty? "Array" else "ArrayOf(#{parse_one(io, key, value.first)})" end when Hash if value.empty? "Hash" else type_struct = key.to_s.gsub(/e?s\z/, '').split('_').map(&:capitalize).join parse(type_struct, value) type_struct end when NilClass "Object" when TrueClass, FalseClass "TrueClass | FalseClass" else value.class.to_s end end |