From f022c42c715dedf35651364e63515bd53079d6aa Mon Sep 17 00:00:00 2001 From: Andrea Rocca Date: Tue, 1 Oct 2024 17:39:21 +0200 Subject: [PATCH] Fix generated associated_object_path for CamelCase class names --- .../associated/associated_generator.rb | 7 +++--- .../generators/associated_generator_test.rb | 22 +++++++++++++++++++ 2 files changed, 26 insertions(+), 3 deletions(-) diff --git a/lib/generators/associated/associated_generator.rb b/lib/generators/associated/associated_generator.rb index b63084a..357d2dc 100644 --- a/lib/generators/associated/associated_generator.rb +++ b/lib/generators/associated/associated_generator.rb @@ -8,6 +8,7 @@ def generate_associated_object_files def connect_associated_object record_file = "#{destination_root}/app/models/#{record_path}.rb" + raise "Record class '#{record_klass}' does not exist" unless File.exist?(record_file) inject_into_class record_file, record_klass do @@ -20,8 +21,8 @@ def connect_associated_object # The `:name` argument can handle model names, but associated object class names aren't singularized. # So these record and associated_object methods prevent that. def record_path = record_klass.downcase.underscore - def record_klass = name.deconstantize + def record_klass = name.camelize.deconstantize - def associated_object_path = associated_object_class.downcase.underscore - def associated_object_class = name.demodulize + def associated_object_path = associated_object_class.underscore + def associated_object_class = name.camelize.demodulize end diff --git a/test/lib/generators/associated_generator_test.rb b/test/lib/generators/associated_generator_test.rb index 28b15e8..5ff27ae 100644 --- a/test/lib/generators/associated_generator_test.rb +++ b/test/lib/generators/associated_generator_test.rb @@ -42,6 +42,28 @@ class Organization RUBY end + test "connects record: Camelized name" do + run_generator ["Organization::SeatsManager"] + + assert_file "app/models/organization.rb", <<~RUBY + class Organization + has_object :seats_manager + end + RUBY + end + + test "connects record: lower_snake_case name" do + run_generator ["organization/seats_manager"] + + assert_file "app/models/organization.rb", <<~RUBY + class Organization + has_object :seats_manager + end + RUBY + end + + + test "raises error if associated record doesn't exist" do assert_raise RuntimeError do run_generator ["Business::Monkey"]