Add Context#to_a

This commit is contained in:
Sijawusz Pur Rahnama 2021-01-04 03:24:44 +01:00
parent 0663fbfa01
commit 521bf7ff28
2 changed files with 52 additions and 15 deletions

View file

@ -1,6 +1,37 @@
require "../../../spec_helper"
def with_foo_context
yield Backtracer::Backtrace::Frame::Context.new(
lineno: 10,
pre: %w[foo bar baz],
line: "violent offender!",
post: %w[boo far faz],
)
end
describe Backtracer::Backtrace::Frame::Context do
describe ".to_a" do
it "works with empty #pre and #post" do
context = Backtracer::Backtrace::Frame::Context.new(
lineno: 1,
pre: %w[],
line: "violent offender!",
post: %w[],
)
context.to_a.should eq(["violent offender!"])
end
it "returns array with #pre, #line and #post strings" do
with_foo_context do |context|
context.to_a.should eq([
"foo", "bar", "baz",
"violent offender!",
"boo", "far", "faz",
])
end
end
end
describe ".to_h" do
it "works with empty #pre and #post" do
context = Backtracer::Backtrace::Frame::Context.new(
@ -13,21 +44,17 @@ describe Backtracer::Backtrace::Frame::Context do
end
it "returns hash with #pre, #line and #post strings" do
context = Backtracer::Backtrace::Frame::Context.new(
lineno: 10,
pre: %w[foo bar baz],
line: "violent offender!",
post: %w[boo far faz],
)
context.to_h.should eq({
7 => "foo",
8 => "bar",
9 => "baz",
10 => "violent offender!",
11 => "boo",
12 => "far",
13 => "faz",
})
with_foo_context do |context|
context.to_h.should eq({
7 => "foo",
8 => "bar",
9 => "baz",
10 => "violent offender!",
11 => "boo",
12 => "far",
13 => "faz",
})
end
end
end
end

View file

@ -15,6 +15,16 @@ module Backtracer
def initialize(@lineno, @pre, @line, @post)
end
# Returns an array composed of context lines from `pre`,
# `line` and `post`.
def to_a : Array(String)
([] of String).tap do |ary|
ary.concat(pre)
ary << line
ary.concat(post)
end
end
# Returns hash with context lines, where line numbers are
# the keys and the lines itself are the values.
def to_h : Hash(Int32, String)