Skip to content

Commit 3232749

Browse files
committed
add rails/prefer_nor_conditions snippet
1 parent 6841fa0 commit 3232749

File tree

4 files changed

+49
-0
lines changed

4 files changed

+49
-0
lines changed

lib/rails/prefer_nor_conditions.rb

+30
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,30 @@
1+
# frozen_string_literal: true
2+
3+
Synvert::Rewriter.new 'rails', 'prefer_nor_conditions' do
4+
configure(parser: Synvert::PARSER_PARSER)
5+
6+
description <<~EOS
7+
Prefer NOR conditions
8+
9+
```ruby
10+
where.not(first_name: nil, last_name: nil)
11+
```
12+
13+
=>
14+
15+
```ruby
16+
where.not(first_name: nil).where.not(last_name: nil)
17+
```
18+
EOS
19+
20+
if_gem 'rails', '>= 6.0'
21+
22+
within_files Synvert::ALL_RUBY_FILES do
23+
find_node '.send[receiver=.send[message=where][arguments.size=0]][message=not][arguments.size=1][arguments.0=.hash[pairs.length>1]]' do
24+
new_source = node.arguments[0].pairs.map do |pair|
25+
"where.not(#{pair.to_source})"
26+
end.join('.')
27+
replace 'receiver.message', :message, :parentheses, with: new_source
28+
end
29+
end
30+
end

lib/rails/upgrade_5_2_to_6_0.rb

+1
Original file line numberDiff line numberDiff line change
@@ -8,6 +8,7 @@
88
EOS
99

1010
add_snippet 'rails', 'convert_update_attributes_to_update'
11+
add_snippet 'rails', 'prefer_nor_conditions'
1112

1213
if_gem 'rails', '>= 6.0'
1314

+17
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,17 @@
1+
# frozen_string_literal: true
2+
3+
require 'spec_helper'
4+
5+
RSpec.describe 'Prefer NOR conditions' do
6+
let(:rewriter_name) { 'rails/prefer_nor_conditions' }
7+
let(:fake_file_path) { 'app/models/user.rb' }
8+
let(:test_content) { <<~EOS }
9+
where.not(first_name: nil, last_name: nil, email: nil)
10+
EOS
11+
12+
let(:test_rewritten_content) { <<~EOS }
13+
where.not(first_name: nil).where.not(last_name: nil).where.not(email: nil)
14+
EOS
15+
16+
include_examples 'convertable'
17+
end

spec/rails/upgrade_5_2_to_6_0_spec.rb

+1
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ class Application < Rails::Application
2121
EOS
2222
before do
2323
load_sub_snippets(%w[rails/convert_update_attributes_to_update])
24+
load_sub_snippets(%w[rails/prefer_nor_conditions])
2425
load_helpers(%w[helpers/set_rails_load_defaults.rb])
2526
end
2627

0 commit comments

Comments
 (0)