Module: RbsActivesupport::Types

Defined in:
lib/rbs_activesupport/types.rb

Class Method Summary collapse

Class Method Details

.guess_type(obj) ⇒ Object



9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
# File 'lib/rbs_activesupport/types.rb', line 9

def guess_type(obj) #: String # rubocop:disable Metrics/AbcSize, Metrics/CyclomaticComplexity, Metrics/PerceivedComplexity
  case obj
  when nil
    "nil"
  when Integer, Float, Symbol, String
    "::#{obj.class.name}" or raise
  when true, false
    "bool"
  when Array
    return "::Array[untyped]" if obj.empty?

    items = obj.map { |e| guess_type(e) }.uniq
    if items.include?("untyped")
      "::Array[untyped]"
    else
      "::Array[#{items.join(" | ")}]"
    end
  when Hash
    return "::Hash[untyped, untyped]" if obj.empty?

    keys = obj.keys.map { |e| guess_type(e) }.uniq
    values = obj.values.map { |e| guess_type(e) }.uniq
    key_type = keys.include?("untyped") ? "untyped" : keys.join(" | ")
    value_type = values.include?("untyped") ? "untyped" : values.join(" | ")
    "::Hash[#{key_type}, #{value_type}]"
  else
    "untyped"
  end
end