Skip to content

Commit

Permalink
Add RegexpNode#options
Browse files Browse the repository at this point in the history
  • Loading branch information
owst committed Sep 26, 2020
1 parent 85c578c commit 22d245f
Show file tree
Hide file tree
Showing 3 changed files with 49 additions and 4 deletions.
4 changes: 4 additions & 0 deletions CHANGELOG.md
Expand Up @@ -2,6 +2,10 @@

## master (unreleased)

### New features

* [#124](https://github.com/rubocop-hq/rubocop-ast/pull/124): Add `RegexpNode#options`. ([@owst][])

## 0.5.1 (2020-09-25)

### Bug fixes
Expand Down
12 changes: 8 additions & 4 deletions lib/rubocop/ast/node/regexp_node.rb
Expand Up @@ -14,19 +14,23 @@ class RegexpNode < Node
o: 0
}.freeze

# Note: The 'o' option is ignored.
#
# @return [Regexp] a regexp of this node
def to_regexp
option = regopt.children.map { |opt| OPTIONS.fetch(opt) }.inject(:|)
Regexp.new(content, option)
Regexp.new(content, options)
end

# @return [RuboCop::AST::Node] a regopt node
def regopt
children.last
end

# Note: The 'o' option is ignored.
#
# @return [Integer] the Regexp option bits as returned by Regexp#options
def options
regopt.children.map { |opt| OPTIONS.fetch(opt) }.inject(0, :|)
end

# @return [String] a string of regexp content
def content
children.select(&:str_type?).map(&:str_content).join
Expand Down
37 changes: 37 additions & 0 deletions spec/rubocop/ast/regexp_node_spec.rb
Expand Up @@ -101,6 +101,43 @@
end
end

describe '#options' do
let(:actual_options) { regexp_node.options }
# rubocop:disable Security/Eval
let(:expected_options) { eval(source).options }
# rubocop:enable Security/Eval

context 'with an empty regexp' do
let(:source) { '//' }

it { expect(actual_options).to eq(expected_options) }
end

context 'with a regexp without option' do
let(:source) { '/.+/' }

it { expect(actual_options).to eq(expected_options) }
end

context 'with a regexp with single option' do
let(:source) { '/.+/i' }

it { expect(actual_options).to eq(expected_options) }
end

context 'with a regexp with multiple options' do
let(:source) { '/.+/ix' }

it { expect(actual_options).to eq(expected_options) }
end

context 'with a regexp with "o" option' do
let(:source) { '/.+/o' }

it { expect(actual_options).to eq(expected_options) }
end
end

describe '#content' do
let(:content) { regexp_node.content }

Expand Down

0 comments on commit 22d245f

Please sign in to comment.