Skip to content

Commit

Permalink
Merge pull request #10139 from dvandersluis/issue/10134
Browse files Browse the repository at this point in the history
[Fix #10134] Update `Style/MutableConstant` to not consider multiline uninterpolated strings as unfrozen in ruby 3.0
  • Loading branch information
koic committed Sep 29, 2021
2 parents 6dfc273 + ed39d2b commit e21a318
Show file tree
Hide file tree
Showing 4 changed files with 37 additions and 3 deletions.
1 change: 1 addition & 0 deletions changelog/fix_update_stylemutableconstant_to_not.md
@@ -0,0 +1 @@
* [#10134](https://github.com/rubocop/rubocop/issues/10134): Update `Style/MutableConstant` to not consider multiline uninterpolated strings as unfrozen in ruby 3.0. ([@dvandersluis][])
6 changes: 5 additions & 1 deletion lib/rubocop/cop/mixin/frozen_string_literal.rb
Expand Up @@ -20,14 +20,18 @@ def frozen_string_literal_comment_exists?

def frozen_string_literal?(node)
frozen_string = if target_ruby_version >= 3.0
node.str_type? || frozen_heredoc?(node)
uninterpolated_string?(node) || frozen_heredoc?(node)
else
FROZEN_STRING_LITERAL_TYPES_RUBY27.include?(node.type)
end

frozen_string && frozen_string_literals_enabled?
end

def uninterpolated_string?(node)
node.str_type? || (node.dstr_type? && node.each_descendant(:begin).none?)
end

def frozen_heredoc?(node)
return false unless node.dstr_type? && node.heredoc?

Expand Down
5 changes: 3 additions & 2 deletions lib/rubocop/cop/style/mutable_constant.rb
Expand Up @@ -21,8 +21,9 @@ module Style
#
# NOTE: Regexp and Range literals are frozen objects since Ruby 3.0.
#
# NOTE: From Ruby 3.0, this cop allows explicit freezing of interpolated
# string literals when `# frozen-string-literal: true` is used.
# NOTE: From Ruby 3.0, interpolated strings are not frozen when
# `# frozen-string-literal: true` is used, so this cop enforces explicit
# freezing for such strings.
#
# NOTE: From Ruby 3.0, this cop allows explicit freezing of constants when
# the `shareable_constant_value` directive is used.
Expand Down
28 changes: 28 additions & 0 deletions spec/rubocop/cop/style/mutable_constant_spec.rb
Expand Up @@ -132,6 +132,25 @@
HERE
RUBY
end

it 'does not register an offense when using a multiline string' do
expect_no_offenses(<<~RUBY)
# frozen_string_literal: true
CONST = 'foo' \
'bar'
RUBY
end

it 'registers an offense when using a multiline string with interpolation' do
expect_offense(<<~'RUBY')
# frozen_string_literal: true
CONST = "#{foo}" \
^^^^^^^^^^ Freeze mutable objects assigned to constants.
'bar'
RUBY
end
end

context 'when the frozen string literal comment is false' do
Expand Down Expand Up @@ -166,6 +185,15 @@
HERE
RUBY
end

it 'does not register an offense when using a multiline string' do
expect_no_offenses(<<~RUBY)
# frozen_string_literal: true
CONST = 'foo' \
'bar'
RUBY
end
end

context 'when the frozen string literal comment is false' do
Expand Down

0 comments on commit e21a318

Please sign in to comment.