Skip to content

Commit

Permalink
More descriptive error message when an associated object class is mis…
Browse files Browse the repository at this point in the history
…sing

Co-authored-by: Garrett Dimon <email@garrettdimon.com>
  • Loading branch information
kaspth and garrettdimon committed May 18, 2024
1 parent 23bd379 commit 46b7c41
Show file tree
Hide file tree
Showing 2 changed files with 9 additions and 1 deletion.
5 changes: 4 additions & 1 deletion lib/active_record/associated_object/object_association.rb
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,10 @@ def extend_source_from(chunks, &block)
module ClassMethods
def has_object(*names, **callbacks)
extend_source_from(names) do |name|
"def #{name}; (@associated_objects ||= {})[:#{name}] ||= #{const_get(name.to_s.camelize)}.new(self); end"
const_get object_name = name.to_s.camelize
"def #{name}; (@associated_objects ||= {})[:#{name}] ||= #{object_name}.new(self); end"
rescue NameError
raise "The #{self}::#{object_name} associated object referenced from #{self} doesn't exist"
end

extend_source_from(names) do |name|
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -18,4 +18,9 @@ class ActiveRecord::AssociatedObject::ObjectAssociationTest < ActiveSupport::Tes
Post.first.touch
assert Post.first.mailroom.touched
end

test "descriptive error when encountering unknown associated object" do
assert_raise { Post.has_object :unknown } => error
assert_equal "The Post::Unknown associated object referenced from Post doesn't exist", error.message
end
end

0 comments on commit 46b7c41

Please sign in to comment.