From 10993d2b1a274c0fedd4e942cf7c56d5b3609caf Mon Sep 17 00:00:00 2001 From: Holger Just Date: Mon, 14 Aug 2017 14:10:08 +0200 Subject: [PATCH] Serialize Rational numbers to a String With this, we are more compatible with the common JSON encoders, including the one on RUby core. --- lib/rackstash/fields/abstract_collection.rb | 4 +++- spec/rackstash/fields/abstract_collection_spec.rb | 5 +++-- 2 files changed, 6 insertions(+), 3 deletions(-) diff --git a/lib/rackstash/fields/abstract_collection.rb b/lib/rackstash/fields/abstract_collection.rb index b1910ca..920b3f4 100644 --- a/lib/rackstash/fields/abstract_collection.rb +++ b/lib/rackstash/fields/abstract_collection.rb @@ -5,6 +5,8 @@ # of the MIT license. See the LICENSE.txt file for details. require 'bigdecimal' +require 'complex' +require 'rational' require 'pathname' require 'uri' @@ -153,7 +155,7 @@ module Rackstash # number and no way to recover other than manually inspecting the # string with the JSON code itself. return value.to_s('F').encode!(Encoding::UTF_8).freeze - when ::Complex + when ::Complex, ::Rational # A complex number can not reliably converted to a float or rational, # thus we always transform it to a String return utf8_encode(value) diff --git a/spec/rackstash/fields/abstract_collection_spec.rb b/spec/rackstash/fields/abstract_collection_spec.rb index c3cca89..ca63d86 100644 --- a/spec/rackstash/fields/abstract_collection_spec.rb +++ b/spec/rackstash/fields/abstract_collection_spec.rb @@ -491,10 +491,11 @@ describe Rackstash::Fields::AbstractCollection do expect(normalize(complex)).to be_frozen end - it 'transforms Rational to Float' do + it 'transforms Rational to String' do rational = Rational(-8, 6) - expect(normalize(rational)).to be_a Float + expect(normalize(rational)).to eql '-4/3' + expect(normalize(rational).encoding).to eql Encoding::UTF_8 expect(normalize(rational)).to be_frozen end