diff --git a/lib/rackstash/fields/array.rb b/lib/rackstash/fields/array.rb index 9c3d9f7..a64ef68 100644 --- a/lib/rackstash/fields/array.rb +++ b/lib/rackstash/fields/array.rb @@ -85,7 +85,6 @@ module Rackstash @raw << normalize(value) self end - alias push << # @return [::Array] deep-transforms the array into a plain Ruby Array def as_json(*) @@ -160,6 +159,20 @@ module Rackstash self end + # Append — Pushes the given object(s) on to the end of this array. All + # values will be normalized before being added. This method returns the + # array itself, so several appends may be chained together. + # + # @param values [::Array] a list of values to append at the end of `self` + # @param scope [Object, nil] if any of the (deeply-nested) values is a + # proc, it will be called in the instance scope of this object (when + # given). + # @return [self] + def push(*values, scope: nil) + concat(values, scope: scope) + end + alias append push + private def implicit(obj) diff --git a/spec/rackstash/fields/array_spec.rb b/spec/rackstash/fields/array_spec.rb index a680204..aed729c 100644 --- a/spec/rackstash/fields/array_spec.rb +++ b/spec/rackstash/fields/array_spec.rb @@ -96,15 +96,13 @@ describe Rackstash::Fields::Array do expect(array[1]).to eql 'normalized' end + it 'can append only one value' do + expect { array.<< 'foo', 'bar' }.to raise_error ArgumentError + end + it 'returns the array' do expect(array << 'value').to equal array end - - it 'can use push as an alias' do - expect(array.push 'value').to equal array - expect(array[0]).to eql 'value' - end - end describe '#as_json' do @@ -270,6 +268,27 @@ describe Rackstash::Fields::Array do end end + describe '#push' do + it 'can append multiple values' do + expect(array.push 'value', 'value2').to equal array + expect(array[0]).to eql 'value' + expect(array[1]).to eql 'value2' + end + + it 'appends arrays as is' do + value = ['hello'] + array.push value + + expect(array[0]).to be_a Rackstash::Fields::Array + expect(array[0].to_a).to eql value + end + + it 'can use append as an alias' do + expect(array.append 'foo').to equal array + expect(array[0]).to eql 'foo' + end + end + describe 'Converter' do it 'creates a new array' do raw = [Time.now, 'foo']