Module: RbsActiverecord::Utils

Instance Method Summary collapse

Instance Method Details

#format(str) ⇒ Object



8
9
10
11
12
13
# File 'lib/rbs_activerecord/utils.rb', line 8

def format(str) #: String
  parsed = RBS::Parser.parse_signature(str)
  StringIO.new.tap do |out|
    RBS::Writer.new(out: out).write(parsed[1] + parsed[2])
  end.string
end

#primary_key_type_for(klass) ⇒ Object



16
17
18
19
20
21
22
23
24
25
26
27
28
# File 'lib/rbs_activerecord/utils.rb', line 16

def primary_key_type_for(klass) #: String  # rubocop:disable Metrics/AbcSize
  case klass.primary_key
  when Array
    primary_keys = klass.primary_key.map(&:to_s)
    types = klass.columns
                 .select { |column| primary_keys.include?(column.name) }
                 .map { |pk| sql_type_to_class(pk.type) }
    "[#{types.join(" | ")}]"
  else
    primary_key = klass.columns.find { |column| column.name == klass.primary_key }
    sql_type_to_class(primary_key.type)
  end
end

#sql_type_to_class(type) ⇒ Object



31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/rbs_activerecord/utils.rb', line 31

def sql_type_to_class(type) #: String  # rubocop:disable Metris/CyclomaticComplexity
  case type
  when :integer
    "::Integer"
  when :float
    "::Float"
  when :decimal
    "::BigDecimal"
  when :string, :text, :citext, :uuid, :binary
    "::String"
  when :datetime
    "::ActiveSupport::TimeWithZone"
  when :date
    "::Date"
  when :time
    "::Time"
  when :boolean
    "bool"
  when :jsonb, :json
    "untyped"
  when :inet
    "::IPAddr"
  else
    "untyped"
  end
end