Skip to content

Commit

Permalink
In ActiveRecordColumns persisted mode, remove T.nilable from reflecte…
Browse files Browse the repository at this point in the history
…d sigs
  • Loading branch information
alex-tan committed Jun 20, 2024
1 parent a4ec8e1 commit 2949288
Show file tree
Hide file tree
Showing 2 changed files with 51 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/tapioca/dsl/helpers/active_record_column_type_helper.rb
Original file line number Diff line number Diff line change
Expand Up @@ -114,7 +114,10 @@ def column_type_for(column_name)
end

if @column_type_option.persisted? && !column&.null
[getter_type, setter_type]
# It's possible that when ActiveModel::Type::Value is used, the signature being reflected on in
# ActiveModelTypeHelper.type_for(type_value) may say the type can be nilable. However, if the type is
# persisted and the column is not nullable, we can assume it's not nilable.
[as_non_nilable_type(getter_type), as_non_nilable_type(setter_type)]
else
getter_type = as_nilable_type(getter_type) unless not_nilable_serialized_column?(column_type)
[getter_type, as_nilable_type(setter_type)]
Expand Down
47 changes: 47 additions & 0 deletions spec/tapioca/dsl/compilers/active_record_columns_spec.rb
Original file line number Diff line number Diff line change
Expand Up @@ -984,6 +984,53 @@ def cost=(value); end
assert_includes(rbi_for(:Post), expected)
end

it "strips T.nilable from reflected signatures method for non-nilable columns in persisted mode" do
add_ruby_file("schema.rb", <<~RUBY)
ActiveRecord::Migration.suppress_messages do
ActiveRecord::Schema.define do
create_table :posts do |t|
t.decimal :cost, null: false
end
end
end
RUBY

add_ruby_file("custom_type.rb", <<~RUBY)
class CustomType
attr_accessor :value
def initialize(number = 0.0)
@value = number
end
class Type < ActiveRecord::Type::Value
extend(T::Sig)
sig { params(value: T.nilable(Numeric)).returns(T.nilable(::CustomType))}
def deserialize(value)
CustomType.new(value) if value
end
end
end
RUBY

add_ruby_file("post.rb", <<~RUBY)
class Post < ActiveRecord::Base
attribute :cost, CustomType::Type.new
end
RUBY

expected = indented(<<~RBI, 4)
sig { returns(::CustomType) }
def cost; end
sig { params(value: ::CustomType).returns(::CustomType) }
def cost=(value); end
RBI

assert_includes(rbi_for(:Post), expected)
end

it "generates id accessors when primary key isn't id" do
add_ruby_file("schema.rb", <<~RUBY)
ActiveRecord::Migration.suppress_messages do
Expand Down

0 comments on commit 2949288

Please sign in to comment.