From 7531af033c61ffbe42c3e0da38d6ed8012fc1ca3 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Piotr=20Nie=C5=82acny?= Date: Thu, 24 Aug 2023 17:26:41 +0200 Subject: [PATCH] Handle standard errors in association generation This commit addresses an issue where standard errors raised during the association generation process were not properly handled, leading to failures in generating RBI files. Now, these errors are captured and logged appropriately, improving the robustness of the association generation process. A new test case has been added to verify this functionality. --- .../compilers/active_record_associations.rb | 4 ++ .../active_record_associations_spec.rb | 42 +++++++++++++++++++ 2 files changed, 46 insertions(+) diff --git a/lib/tapioca/dsl/compilers/active_record_associations.rb b/lib/tapioca/dsl/compilers/active_record_associations.rb index d401d4d2f..85669d97a 100644 --- a/lib/tapioca/dsl/compilers/active_record_associations.rb +++ b/lib/tapioca/dsl/compilers/active_record_associations.rb @@ -173,6 +173,10 @@ def populate_associations(mod) add_error(<<~MSG.strip) Cannot generate association `#{declaration(reflection)}` on `#{constant}` since the constant `#{error.class_name}` does not exist. MSG + rescue StandardError => error + add_error(<<~MSG.strip) + Cannot generate association `#{association_name}` on `#{constant}` because of `#{error}`.". + MSG end end diff --git a/spec/tapioca/dsl/compilers/active_record_associations_spec.rb b/spec/tapioca/dsl/compilers/active_record_associations_spec.rb index 274c5ce26..72bff238e 100644 --- a/spec/tapioca/dsl/compilers/active_record_associations_spec.rb +++ b/spec/tapioca/dsl/compilers/active_record_associations_spec.rb @@ -1337,6 +1337,48 @@ def reload_post; end expect_dsl_compiler_errors! end + it "generates RBI file for monkey patches reflections" do + add_ruby_file("schema.rb", <<~RUBY) + ActiveRecord::Migration.suppress_messages do + ActiveRecord::Schema.define do + create_table :posts do |t| + end + end + end + RUBY + + add_ruby_file("custom_reflection.rb", <<~RUBY) + class CustomReflection + def parent_reflection + end + end + RUBY + + add_ruby_file("post.rb", <<~RUBY) + class Post < ActiveRecord::Base + ::ActiveRecord::Reflection.add_reflection(self, :monkey, CustomReflection.new) + end + RUBY + + expected = <<~RBI + # typed: strong + + class Post + include GeneratedAssociationMethods + + module GeneratedAssociationMethods; end + end + RBI + + assert_equal(expected, rbi_for(:Post)) + + assert_equal(1, generated_errors.size) + + assert_match(Regexp.new(<<~MSG.strip), generated_errors.first) + Cannot generate association `monkey` on `Post` because of `undefined method `collection?.* + MSG + end + it "generates RBI file for broken associations" do add_ruby_file("schema.rb", <<~RUBY) ActiveRecord::Migration.suppress_messages do