From 011249bb754a513ac117ef6f0fe0af3fe19d9856 Mon Sep 17 00:00:00 2001 From: Holger Just Date: Mon, 7 Aug 2017 22:49:39 +0200 Subject: [PATCH] Add Flows#first and Flows#last --- lib/rackstash/flows.rb | 38 ++++++++++++++++++++++++++++++++++++ spec/rackstash/flows_spec.rb | 38 ++++++++++++++++++++++++++++++++++++ 2 files changed, 76 insertions(+) diff --git a/lib/rackstash/flows.rb b/lib/rackstash/flows.rb index 5dc130e..6b61317 100644 --- a/lib/rackstash/flows.rb +++ b/lib/rackstash/flows.rb @@ -82,12 +82,50 @@ module Rackstash @flows.empty? end + # @overload first + # @return [Flow, nil] the first flow. If the list is empty, `nil` is + # returned. + # + # @overload first(n) + # @param n [Integer] the number of flows to return + # @return [Array] the first `n` flows. If the list is empty, an + # empty array is returned. + # + # @return [Flow, Array, nil] + # @see #last #last for the opposite effect. + def first(n = UNDEFINED) + if UNDEFINED.equal? n + @flows.first + else + @flows.first(n) + end + end + # @return [String] a string representation of `self` def inspect id_str = Object.instance_method(:to_s).bind(self).call[2..-2] "#<#{id_str} #{self}>" end + # @overload last + # @return [Flow, nil] the last flow. If the list is empty, `nil` is + # returned. + # + # @overload last(n) + # @param n [Integer] the number of flows to return + # @return [Array] the last `n` flows. If the list is empty, an empty + # array is returned. + # + # @return [Flow, Array, nil] + # @see #first #first for the opposite effect. + def last(n = UNDEFINED) + if UNDEFINED.equal? n + @flows.last + else + @flows.last(n) + end + end + # @return [Integer] the number of elements in `self`. May be zero. def length @flows.length diff --git a/spec/rackstash/flows_spec.rb b/spec/rackstash/flows_spec.rb index d8f5f64..0372135 100644 --- a/spec/rackstash/flows_spec.rb +++ b/spec/rackstash/flows_spec.rb @@ -161,6 +161,25 @@ describe Rackstash::Flows do end end + describe '#first' do + it 'gets the first flow' do + expect(flows.first).to be_nil + + flows << a_flow + expect(flows.first).to equal flows[0] + end + + it 'gets a number of flows' do + flow_list = [a_flow, a_flow, a_flow] + flow_list.each do |flow| + flows << flow + end + + expect(flows.first(2)).to eql flow_list[0, 2] + expect(flows.first(4)).to eql flow_list + end + end + describe '#inspect' do it 'formats the object' do expect(flows).to receive(:to_s).and_return('[""]') @@ -170,6 +189,25 @@ describe Rackstash::Flows do end end + describe '#last' do + it 'gets the last flow' do + expect(flows.last).to be_nil + + flows << a_flow + expect(flows.last).to equal flows[0] + end + + it 'gets a number of flows' do + flow_list = [a_flow, a_flow, a_flow] + flow_list.each do |flow| + flows << flow + end + + expect(flows.last(2)).to eql flow_list[1, 2] + expect(flows.last(4)).to eql flow_list + end + end + describe '#length' do it 'returns the number of flows' do expect { flows << a_flow }