From 735c3c0059c3a77872d2932308f621f833c282db Mon Sep 17 00:00:00 2001 From: Sean Doyle Date: Sun, 2 Nov 2025 23:29:19 -0500 Subject: [PATCH] Prefix: restore variable for the sake of error logging Resolve a 13 year old bug (according to a [comment on 7589c1a][]) by re-declaring the `code` variable that was unintentionally removed in [da74c4f][]. Prior to this commit, the following error is raised when setting `.prefix = nil`: ``` NameError: undefined local variable or method `code' for class Person ``` However, the error should be a `NoMethodError` from calling `String#gsub` on `nil`, rather than the `NameError` raised by the missing variable. The `NoMethodError` can still be improved upon, but this commit aims to restore the logging visibility first-and-foremost. [comment on 7589c1a]: https://github.com/rails/activeresource/commit/7589c1a3c234ebb12880b81b1999b0cbe97b8402#r2381147 [da74c4f]: https://github.com/rails/activeresource/commit/da74c4ffcfcafdd36c5589948a5ea7eb55af60d0#diff-5d3e28bbfdc782e5e5501903dd1171cc83b1aef685cc5b0547f527ec2573f989R58 --- lib/active_resource/base.rb | 10 ++++++---- test/cases/base_test.rb | 11 +++++++++++ 2 files changed, 17 insertions(+), 4 deletions(-) diff --git a/lib/active_resource/base.rb b/lib/active_resource/base.rb index edf92e5c25..c85edcfca3 100644 --- a/lib/active_resource/base.rb +++ b/lib/active_resource/base.rb @@ -818,12 +818,14 @@ def prefix=(value = "/") # Clear prefix parameters in case they have been cached @prefix_parameters = nil + code, line = <<-RUBY_EVAL, __LINE__ + 1 + def prefix_source() "#{value}" end + def prefix(options={}) "#{prefix_call}" end + RUBY_EVAL + silence_warnings do # Redefine the new methods. - instance_eval <<-RUBY_EVAL, __FILE__, __LINE__ + 1 - def prefix_source() "#{value}" end - def prefix(options={}) "#{prefix_call}" end - RUBY_EVAL + instance_eval code, __FILE__, line end rescue Exception => e logger.error "Couldn't set prefix: #{e}\n #{code}" if logger diff --git a/test/cases/base_test.rb b/test/cases/base_test.rb index 462920ac92..40b4aa8d26 100644 --- a/test/cases/base_test.rb +++ b/test/cases/base_test.rb @@ -43,6 +43,17 @@ def test_site_accessor_accepts_uri_or_string_argument assert_equal site, Person.site end + def test_prefix_error_message + previous_prefix = Person.prefix + previous_logger, Person.logger = Person.logger, ActiveSupport::Logger.new(output = StringIO.new) + + error = assert_raises(NoMethodError) { Person.prefix = nil } + assert_equal "Couldn't set prefix: #{error}", output.string.strip + ensure + Person.prefix = previous_prefix + Person.logger = previous_logger + end + def test_should_use_site_prefix_and_credentials assert_equal "http://foo:bar@beast.caboo.se", Forum.site.to_s assert_equal "http://foo:bar@beast.caboo.se/forums/:forum_id", Topic.site.to_s