From eecc2bb41c380d762a2212b9a4ce19a8b54c453c Mon Sep 17 00:00:00 2001 From: Earlopain <14981592+Earlopain@users.noreply.github.com> Date: Mon, 12 Aug 2024 18:25:52 +0200 Subject: [PATCH] Fix an error for `Rails/RenderPlainText` when the content type is passed as a constant Or other nodes that don't respond to `value` like local variables --- changelog/fix_error_rails_render_plain_text_constant.md | 1 + lib/rubocop/cop/rails/render_plain_text.rb | 9 ++++++--- spec/rubocop/cop/rails/render_plain_text_spec.rb | 6 ++++++ 3 files changed, 13 insertions(+), 3 deletions(-) create mode 100644 changelog/fix_error_rails_render_plain_text_constant.md diff --git a/changelog/fix_error_rails_render_plain_text_constant.md b/changelog/fix_error_rails_render_plain_text_constant.md new file mode 100644 index 0000000000..0fbab1d458 --- /dev/null +++ b/changelog/fix_error_rails_render_plain_text_constant.md @@ -0,0 +1 @@ +* [#1325](https://github.com/rubocop/rubocop-rails/pull/1325): Fix an error for `Rails/RenderPlainText` when the content type is passed as a constant. ([@earlopain][]) diff --git a/lib/rubocop/cop/rails/render_plain_text.rb b/lib/rubocop/cop/rails/render_plain_text.rb index 0736bb3c28..ebf69b742c 100644 --- a/lib/rubocop/cop/rails/render_plain_text.rb +++ b/lib/rubocop/cop/rails/render_plain_text.rb @@ -53,9 +53,12 @@ def find_content_type(node) node.pairs.find { |p| p.key.value.to_sym == :content_type } end - def compatible_content_type?(node) - (node && node.value.value == 'text/plain') || - (!node && !cop_config['ContentTypeCompatibility']) + def compatible_content_type?(pair_node) + if pair_node.nil? + !cop_config['ContentTypeCompatibility'] + elsif pair_node.value.respond_to?(:value) + pair_node.value.value == 'text/plain' + end end def replacement(rest_options, option_value) diff --git a/spec/rubocop/cop/rails/render_plain_text_spec.rb b/spec/rubocop/cop/rails/render_plain_text_spec.rb index 4d69c6edeb..084df4b8f3 100644 --- a/spec/rubocop/cop/rails/render_plain_text_spec.rb +++ b/spec/rubocop/cop/rails/render_plain_text_spec.rb @@ -19,6 +19,12 @@ RUBY end + it 'does not register an offense when `content_type` is a constant' do + expect_no_offenses(<<~RUBY) + render text: 'Ruby!', content_type: Foo + RUBY + end + it 'does not register an offense when using `render plain:`' do expect_no_offenses(<<~RUBY) render plain: 'Ruby!'