Skip to content

Commit afc2da1

Browse files
committed
Make Parser#output alias of Parser#run
This also makes sure that output is only calculated once.
1 parent 907b271 commit afc2da1

2 files changed

Lines changed: 28 additions & 10 deletions

File tree

lib/code_breaker/parser.rb

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -4,26 +4,30 @@
44
module CodeBreaker
55
class Parser
66

7-
attr_reader :input, :output
7+
attr_reader :input
88

99
def initialize(code)
1010
@input = code.to_s.strip
1111
end
1212

1313
def run
14-
parsed = ::Parser::CurrentRuby.parse(@input)
15-
nodes = parsed.loc.node.children
16-
children = nodes[1].children
17-
18-
result = parse(children)
19-
@output = cleanup(result)
14+
@output ||= parse(@input)
2015
end
2116

17+
alias :output :run
18+
2219
private
2320

24-
def parse(nodes)
21+
def parse(input)
22+
parsed_ast = ::Parser::CurrentRuby.parse(input)
23+
nodes = parsed_ast.loc.node.children[1].children
24+
result = parse_nodes(nodes)
25+
cleanup(result)
26+
end
27+
28+
def parse_nodes(nodes)
2529
nodes.map do |node|
26-
node.respond_to?(:children) ? parse(node.children).to_a : node
30+
node.respond_to?(:children) ? parse_nodes(node.children).to_a : node
2731
end
2832
end
2933

spec/parser_spec.rb

Lines changed: 15 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,13 +2,27 @@
22

33
describe CodeBreaker::Parser do
44

5-
let(:code_snippet) { 'gem_name = "code_breaker"' }
5+
let(:code_snippet) { 'sum = "2".to_i + 3' }
6+
let(:output) { [String, :to_i, :+, Fixnum] }
7+
68
subject { CodeBreaker::Parser.new(code_snippet) }
79

810
it { is_expected.to respond_to :run }
911
it { is_expected.to respond_to :input }
1012
it { is_expected.to respond_to :output }
1113

14+
describe 'input' do
15+
it 'returns the code snippet the parser was instanciated with' do
16+
expect(subject.input).to eq code_snippet
17+
end
18+
end
19+
20+
describe 'output' do
21+
it 'is an alias method for #run' do
22+
expect(subject.method(:output)).to eq subject.method(:run)
23+
end
24+
end
25+
1226
describe '#run' do
1327
it 'returns an Array' do
1428
expect(subject.run).to be_an Array

0 commit comments

Comments
 (0)