diff --git a/CHANGELOG.md b/CHANGELOG.md index 7762bc3b7..3a0ae1d3d 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -2,6 +2,8 @@ ## master (unreleased) +* [#4](https://github.com/rubocop-hq/rubocop-ast/issues/4): Add `interpolation?` for `RegexpNode`. ([@tejasbubane][]) + ## 0.0.3 (2020-05-15) ### Changes diff --git a/lib/rubocop/ast/node/regexp_node.rb b/lib/rubocop/ast/node/regexp_node.rb index 5ca476e08..bf494d05c 100644 --- a/lib/rubocop/ast/node/regexp_node.rb +++ b/lib/rubocop/ast/node/regexp_node.rb @@ -31,6 +31,11 @@ def regopt def content children.select(&:str_type?).map(&:str_content).join end + + # @return [Bool] if regexp contains interpolation + def interpolation? + children.select(&:begin_type?).any? + end end end end diff --git a/spec/rubocop/ast/regexp_node_spec.rb b/spec/rubocop/ast/regexp_node_spec.rb index 1897f5976..38c367994 100644 --- a/spec/rubocop/ast/regexp_node_spec.rb +++ b/spec/rubocop/ast/regexp_node_spec.rb @@ -140,4 +140,24 @@ it { expect(content).to eq("\n.+\n") } end end + + describe '#has_interpolation?' do + context 'with direct variable interpoation' do + let(:source) { '/\n\n#{foo}(abc)+/' } + + it { expect(regexp_node.interpolation?).to eq(true) } + end + + context 'with regexp quote' do + let(:source) { '/\n\n#{Regexp.quote(foo)}(abc)+/' } + + it { expect(regexp_node.interpolation?).to eq(true) } + end + + context 'with no interpolation returns false' do + let(:source) { '/a{3,6}/' } + + it { expect(regexp_node.interpolation?).to eq(false) } + end + end end