Class: ActiveRecordColumnTypeHelper

Inherits:
Object
  • Object
show all
Extended by:
T::Sig
Defined in:
lib/tapioca/helpers/active_record_column_type_helper.rb

Overview

typed: strict frozen_string_literal: true

Instance Method Summary collapse

Constructor Details

#initialize(constant) ⇒ ActiveRecordColumnTypeHelper

Returns a new instance of ActiveRecordColumnTypeHelper.



8
9
10
# File 'lib/tapioca/helpers/active_record_column_type_helper.rb', line 8

def initialize(constant)
  @constant = constant
end

Instance Method Details

#type_for(column_name) ⇒ Object



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
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
# File 'lib/tapioca/helpers/active_record_column_type_helper.rb', line 13

def type_for(column_name)
  return ["T.untyped", "T.untyped"] if do_not_generate_strong_types?(@constant)

  column_type = @constant.attribute_types[column_name]

  getter_type =
    case column_type
    when defined?(MoneyColumn) && MoneyColumn::ActiveRecordType
      "::Money"
    when ActiveRecord::Type::Integer
      "::Integer"
    when ActiveRecord::Type::String
      "::String"
    when ActiveRecord::Type::Date
      "::Date"
    when ActiveRecord::Type::Decimal
      "::BigDecimal"
    when ActiveRecord::Type::Float
      "::Float"
    when ActiveRecord::Type::Boolean
      "T::Boolean"
    when ActiveRecord::Type::DateTime, ActiveRecord::Type::Time
      "::DateTime"
    when ActiveRecord::AttributeMethods::TimeZoneConversion::TimeZoneConverter
      "::ActiveSupport::TimeWithZone"
    else
      handle_unknown_type(column_type)
    end

  column = @constant.columns_hash[column_name]
  setter_type = getter_type

  if column&.null
    return ["T.nilable(#{getter_type})", "T.nilable(#{setter_type})"]
  end

  if column_name == @constant.primary_key ||
      column_name == "created_at" ||
      column_name == "updated_at"
    getter_type = "T.nilable(#{getter_type})"
  end

  [getter_type, setter_type]
end