Skip to content

Commit ca5886e

Browse files
committed
Fix StrNode#last_line and StrNode#line_count for heredocs
1 parent 0d5505c commit ca5886e

File tree

3 files changed

+85
-0
lines changed

3 files changed

+85
-0
lines changed

CHANGELOG.md

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,10 @@
22

33
## master (unreleased)
44

5+
### Bug fixes
6+
7+
* [#40](https://github.com/rubocop-hq/rubocop-ast/pull/40): Fix `StrNode#last_line` and `StrNode#line_count` for heredocs. ([@fatkodima][])
8+
59
## 1.3.0 (2020-11-30)
610

711
### Changes

lib/rubocop/ast/node/str_node.rb

Lines changed: 12 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -11,6 +11,18 @@ class StrNode < Node
1111
def heredoc?
1212
loc.is_a?(Parser::Source::Map::Heredoc)
1313
end
14+
15+
def last_line
16+
if heredoc?
17+
loc.heredoc_end.line
18+
else
19+
super
20+
end
21+
end
22+
23+
def line_count
24+
last_line - first_line + 1
25+
end
1426
end
1527
end
1628
end

spec/rubocop/ast/str_node_spec.rb

Lines changed: 69 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -56,4 +56,73 @@
5656
it { is_expected.to be_heredoc }
5757
end
5858
end
59+
60+
describe '#first_line' do
61+
context 'with a normal string' do
62+
let(:source) { "'foo'" }
63+
64+
it { expect(str_node.first_line).to eq(1) }
65+
end
66+
67+
context 'with a heredoc' do
68+
let(:source) do
69+
<<~RUBY
70+
<<-CODE
71+
foo
72+
bar
73+
CODE
74+
RUBY
75+
end
76+
77+
it { expect(str_node.first_line).to eq(1) }
78+
end
79+
end
80+
81+
describe '#last_line' do
82+
context 'with a normal string' do
83+
let(:source) do
84+
['"foo"\\',
85+
'"bar"'].join("\n")
86+
end
87+
88+
it { expect(str_node.last_line).to eq(2) }
89+
end
90+
91+
context 'with a heredoc' do
92+
let(:source) do
93+
<<~RUBY
94+
<<-CODE
95+
foo
96+
bar
97+
CODE
98+
RUBY
99+
end
100+
101+
it { expect(str_node.last_line).to eq(4) }
102+
end
103+
end
104+
105+
describe '#line_count' do
106+
context 'with a normal string' do
107+
let(:source) do
108+
['"foo"\\',
109+
'"bar"'].join("\n")
110+
end
111+
112+
it { expect(str_node.line_count).to eq(2) }
113+
end
114+
115+
context 'with a heredoc' do
116+
let(:source) do
117+
<<~RUBY
118+
<<-CODE
119+
foo
120+
bar
121+
CODE
122+
RUBY
123+
end
124+
125+
it { expect(str_node.line_count).to eq(4) }
126+
end
127+
end
59128
end

0 commit comments

Comments
 (0)