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.
8 9 10 |
# File 'lib/type_struct/generator.rb', line 8 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
23 24 25 26 27 28 29 30 31 32 |
# File 'lib/type_struct/generator.rb', line 23 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
34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 |
# File 'lib/type_struct/generator.rb', line 34 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(/s\z/, '').split('_').map(&:capitalize).join parse(type_struct, value) type_struct end when Integer "Integer" when NilClass "Object" when TrueClass, FalseClass "TrueClass | FalseClass" else value.class.to_s end end |