From b17bfb7072c2cd8aba9aa2cb5947795cb96370cf Mon Sep 17 00:00:00 2001 From: viralpraxis Date: Sat, 3 May 2025 23:55:27 +0300 Subject: [PATCH] Fix `Rails/TimeZone` cop error on invalid string literal encoding In some cases (e.g. for testing purposes) we might to want to use invalid string literal -- in that case IMO we should not register an offense. --- ...e_cop_error_on_invalid_string_literal_encoding.md | 1 + lib/rubocop/cop/rails/time_zone.rb | 4 +++- spec/rubocop/cop/rails/time_zone_spec.rb | 12 ++++++++++++ 3 files changed, 16 insertions(+), 1 deletion(-) create mode 100644 changelog/fix_rails_time_zone_cop_error_on_invalid_string_literal_encoding.md diff --git a/changelog/fix_rails_time_zone_cop_error_on_invalid_string_literal_encoding.md b/changelog/fix_rails_time_zone_cop_error_on_invalid_string_literal_encoding.md new file mode 100644 index 0000000000..4a8e0a0357 --- /dev/null +++ b/changelog/fix_rails_time_zone_cop_error_on_invalid_string_literal_encoding.md @@ -0,0 +1 @@ +* [#1475](https://github.com/rubocop/rubocop-rails/pull/1475): Fix `Rails/TimeZone` cop error on invalid string literal encoding. ([@viralpraxis][]) diff --git a/lib/rubocop/cop/rails/time_zone.rb b/lib/rubocop/cop/rails/time_zone.rb index 80d7d97790..bdad834926 100644 --- a/lib/rubocop/cop/rails/time_zone.rb +++ b/lib/rubocop/cop/rails/time_zone.rb @@ -135,7 +135,9 @@ def check_time_node(klass, node) end def attach_timezone_specifier?(date) - date.respond_to?(:value) && TIMEZONE_SPECIFIER.match?(date.value.to_s) + return false unless date.respond_to?(:value) + + !date.value.to_s.valid_encoding? || TIMEZONE_SPECIFIER.match?(date.value.to_s) end def build_message(klass, method_name, node) diff --git a/spec/rubocop/cop/rails/time_zone_spec.rb b/spec/rubocop/cop/rails/time_zone_spec.rb index 41de6bb92b..58618cad51 100644 --- a/spec/rubocop/cop/rails/time_zone_spec.rb +++ b/spec/rubocop/cop/rails/time_zone_spec.rb @@ -1,9 +1,19 @@ # frozen_string_literal: true RSpec.describe RuboCop::Cop::Rails::TimeZone, :config do + shared_examples 'with invalid timezone literal encoding' do + it 'does not register an offense' do + expect_no_offenses(<<~'RUBY') + Time.new("l\366, 26 maj 2001 00:15:58") + RUBY + end + end + context 'when EnforcedStyle is "strict"' do let(:cop_config) { { 'EnforcedStyle' => 'strict' } } + include_context 'with invalid timezone literal encoding' + it 'registers an offense for Time.now' do expect_offense(<<~RUBY) Time.now @@ -334,6 +344,8 @@ context 'when EnforcedStyle is "flexible"' do let(:cop_config) { { 'EnforcedStyle' => 'flexible' } } + include_context 'with invalid timezone literal encoding' + it 'registers an offense for Time.now' do expect_offense(<<~RUBY) Time.now