From 521bf7ff28a71c6e015ab7b2fff221e2e0b18cf9 Mon Sep 17 00:00:00 2001 From: Sijawusz Pur Rahnama Date: Mon, 4 Jan 2021 03:24:44 +0100 Subject: [PATCH] Add Context#to_a --- .../backtrace/frame/context_spec.cr | 57 ++++++++++++++----- src/backtracer/backtrace/frame/context.cr | 10 ++++ 2 files changed, 52 insertions(+), 15 deletions(-) diff --git a/spec/backtracer/backtrace/frame/context_spec.cr b/spec/backtracer/backtrace/frame/context_spec.cr index 2ee0a82..1ec0a74 100644 --- a/spec/backtracer/backtrace/frame/context_spec.cr +++ b/spec/backtracer/backtrace/frame/context_spec.cr @@ -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 diff --git a/src/backtracer/backtrace/frame/context.cr b/src/backtracer/backtrace/frame/context.cr index 12a9e1b..d5d22aa 100644 --- a/src/backtracer/backtrace/frame/context.cr +++ b/src/backtracer/backtrace/frame/context.cr @@ -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)