1
0
mirror of https://github.com/meineerde/rackstash.git synced 2025-10-17 14:01:01 +00:00

Add Message#copy_with to create an adjusted copy of an exising message

You can overwrite any (or none) of the existing fields to create a new
frozen copy of a message object.
This commit is contained in:
Holger Just 2017-08-07 23:04:10 +02:00
parent 011249bb75
commit eb93d70468
2 changed files with 46 additions and 0 deletions

View File

@ -58,6 +58,20 @@ module Rackstash
freeze freeze
end end
# Create a new Message object based on the values in `self`, optionally
# overwriting any of the them.
#
# @param (see #initialize)
# @return [Message] a new Message
def copy_with(message = nil, severity: nil, time: nil, progname: nil)
self.class.new(
message.nil? ? self.message : message,
severity: severity.nil? ? self.severity : severity,
time: time.nil? ? self.time : time,
progname: progname.nil? ? self.progname : progname
)
end
# @return [String] the human readable label for the {#severity}. # @return [String] the human readable label for the {#severity}.
# @see Rackstash.severity_label # @see Rackstash.severity_label
def severity_label def severity_label

View File

@ -12,6 +12,9 @@ require 'json'
require 'rackstash/message' require 'rackstash/message'
describe Rackstash::Message do describe Rackstash::Message do
let(:message_args) { {} }
let(:message) { described_class.new 'message', **message_args }
describe '#initialize' do describe '#initialize' do
it 'encodes the message as UTF-8' do it 'encodes the message as UTF-8' do
utf8_str = 'Dönerstraße' utf8_str = 'Dönerstraße'
@ -56,6 +59,35 @@ describe Rackstash::Message do
end end
end end
describe '#copy_with' do
it 'creates a new message instance' do
expect(message.copy_with).to be_instance_of described_class
expect(message.copy_with.message).to equal message.message
expect(message.copy_with.severity).to equal message.severity
expect(message.copy_with.progname).to equal message.progname
expect(message.copy_with.time).to equal message.time
expect(message.copy_with).not_to equal message
end
it 'can overwrite the message' do
expect(message.copy_with('new stuff').message).to eql 'new stuff'
end
it 'can overwrite the severity' do
expect(message.copy_with(severity: 3).severity).to eql 3
end
it 'can overwrite the progname' do
expect(message.copy_with(progname: 'blar').progname).to eql 'blar'
end
it 'can overwrite the progname' do
time = Time.now.freeze
expect(message.copy_with(time: time).time).to equal time
end
end
describe '#message' do describe '#message' do
it 'is aliased to to_str' do it 'is aliased to to_str' do
message = described_class.new('hello world') message = described_class.new('hello world')