From ad038f4317fc51f479a40e89dbf35f69e696e700 Mon Sep 17 00:00:00 2001 From: Holger Just Date: Fri, 10 Feb 2017 23:22:18 +0100 Subject: [PATCH] Add Rackstash::Fields::Array#<< to add a value at the end of the array --- lib/rackstash/fields/array.rb | 11 +++++++++++ spec/rackstash/fields/array_spec.rb | 18 ++++++++++++++++++ 2 files changed, 29 insertions(+) diff --git a/lib/rackstash/fields/array.rb b/lib/rackstash/fields/array.rb index 368bfde..79786bc 100644 --- a/lib/rackstash/fields/array.rb +++ b/lib/rackstash/fields/array.rb @@ -20,6 +20,17 @@ module Rackstash @raw[index] = normalize(value) end + # Add a given value at the end of the array + # + # @param value [#call, Object] any value which can be serialized to JSON. + # The value will be normalized before being added so that only JSON- + # compatible objects are added into the array. + # @return [self] + def <<(value) + @raw << normalize(value) + self + end + def as_json(*) @raw.map { |value| value.is_a?(AbstractCollection) ? value.as_json : value diff --git a/spec/rackstash/fields/array_spec.rb b/spec/rackstash/fields/array_spec.rb index 4f3dafb..3f46813 100644 --- a/spec/rackstash/fields/array_spec.rb +++ b/spec/rackstash/fields/array_spec.rb @@ -30,6 +30,24 @@ describe Rackstash::Fields::Array do end end + describe '#<<' do + it 'normalized the value' do + expect(array).to receive(:normalize).with('value').twice.and_return('normalized') + + array << 'value' + expect(array[0]).to eql 'normalized' + expect(array[1]).to be nil + + array << 'value' + expect(array[0]).to eql 'normalized' + expect(array[1]).to eql 'normalized' + end + + it 'returns the array' do + expect(array << 'value').to equal array + end + end + describe '#as_json' do before do array[0] = 'value'