Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add RegexpNode#options #124

Merged
merged 1 commit into from Sep 26, 2020
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Jump to
Jump to file
Failed to load files.
Diff view
Diff view
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