Class: TypeStruct::Generator

Inherits:
Object
  • Object
show all
Defined in:
lib/type_struct/generator.rb

Overview

Respects:

http://json2struct.mervine.net/
https://mholt.github.io/json-to-go/

Instance Method Summary collapse

Constructor Details

#initializeGenerator

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
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
# 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|
    case value
    when Array
      if value.empty?
        io.puts "  #{key}: Array,"
      else
        type_struct = key.to_s.gsub(/s\z/, '').split('_').map(&:capitalize).join
        parse(type_struct, value.first)
        io.puts "  #{key}: ArrayOf(#{type_struct}),"
      end
    when Hash
      if value.empty?
        io.puts "  #{key}: Hash,"
      else
        type_struct = key.to_s.gsub(/e?s\z/, '').split('_').map(&:capitalize).join
        parse(type_struct, value)
        io.puts "  #{key}: #{type_struct},"
      end
    when NilClass
      io.puts "  #{key}: Object,"
    when TrueClass, FalseClass
      io.puts "  #{key}: TrueClass | FalseClass,"
    else
      io.puts "  #{key}: #{value.class},"
    end
  end
  io.puts ")"
  @io.print io.string
  @io.string
end