diff --git a/lib/rackstash/filters/rename.rb b/lib/rackstash/filters/rename.rb new file mode 100644 index 0000000..780604e --- /dev/null +++ b/lib/rackstash/filters/rename.rb @@ -0,0 +1,42 @@ +# frozen_string_literal: true +# +# Copyright 2017 Holger Just +# +# This software may be modified and distributed under the terms +# of the MIT license. See the LICENSE.txt file for details. + +module Rackstash + module Filters + # Rename one or more fields in the given event. + # + # @example + # Rackstash::Flow.new(STDOUT) do + # # Renames the "HOST_OR_IP" field to "client_ip" + # filter :rename, "HOST_OR_IP" => "client_ip" + # end + class Rename + # @param spec [Hash<#to_s => #to_s>] a `Hash` specifying how fields should + # be renamed, with the existing field name as a hash key and the new + # field name as the respective value. + def initialize(spec) + @rename = {} + Hash(spec).each_pair do |key, value| + @rename[key.to_s] = value.to_s + end + end + + # Rename fields in the event to a new name. If a field was not found, + # it will be ignored. + # + # @param event [Hash] an event hash + # return [Hash] the given `event` with the fields renamed + def call(event) + @rename.each_pair do |old_key, new_key| + next unless event.key?(old_key) + event[new_key] = event.delete(old_key) + end + event + end + end + end +end diff --git a/spec/rackstash/filters/rename_spec.rb b/spec/rackstash/filters/rename_spec.rb new file mode 100644 index 0000000..219a31a --- /dev/null +++ b/spec/rackstash/filters/rename_spec.rb @@ -0,0 +1,47 @@ +# frozen_string_literal: true +# +# Copyright 2017 Holger Just +# +# This software may be modified and distributed under the terms +# of the MIT license. See the LICENSE.txt file for details. + +require 'spec_helper' + +require 'rackstash/filters/rename' + +describe Rackstash::Filters::Rename do + let(:event) { + { + 'foo' => 'foo value', + 'bar' => 'bar value' + } + } + + def filter!(spec) + described_class.new(spec).call(event) + end + + it 'renames existing fields' do + filter!('foo' => 'awesome') + expect(event).to eql 'awesome' => 'foo value', 'bar' => 'bar value' + end + + it 'it ignores missing fields' do + filter!('unknown' => 'ohnoes') + expect(event).to eql 'foo' => 'foo value', 'bar' => 'bar value' + end + + it 'stringifies spec values' do + filter!(foo: :bam) + expect(event).to eql 'bam' => 'foo value', 'bar' => 'bar value' + end + + it 'overwrites conflicting keys' do + filter!('foo' => 'bar') + expect(event).to eql 'bar' => 'foo value' + end + + it 'returns the given event object' do + expect(filter!('bar' => 'baz')).to equal event + end +end