From a686d2dcaa57122a186e0291b9987e7c9aa72e1f Mon Sep 17 00:00:00 2001 From: Lewis Buckley Date: Sun, 9 Jul 2023 12:04:28 +0100 Subject: [PATCH] Make boolean storage more efficient Rather than store the boolean as a string, store it as a 1 or 0. This is more efficient in terms of storage. This change is backwards-compatible, so existing boolean values will continue to work as expected. --- lib/kredis/type/boolean.rb | 11 +++++++++++ lib/kredis/type_casting.rb | 5 +++-- test/types/flag_test.rb | 1 + test/types/scalar_test.rb | 16 ++++++++++++++++ 4 files changed, 31 insertions(+), 2 deletions(-) create mode 100644 lib/kredis/type/boolean.rb diff --git a/lib/kredis/type/boolean.rb b/lib/kredis/type/boolean.rb new file mode 100644 index 0000000..526c305 --- /dev/null +++ b/lib/kredis/type/boolean.rb @@ -0,0 +1,11 @@ +# frozen_string_literal: true + +module Kredis + module Type + class Boolean < ActiveModel::Type::Boolean + def serialize(value) + super ? 1 : 0 + end + end + end +end diff --git a/lib/kredis/type_casting.rb b/lib/kredis/type_casting.rb index 412d485..725618d 100644 --- a/lib/kredis/type_casting.rb +++ b/lib/kredis/type_casting.rb @@ -1,7 +1,8 @@ require "json" require "active_model/type" -require "kredis/type/json" +require "kredis/type/boolean" require "kredis/type/datetime" +require "kredis/type/json" module Kredis::TypeCasting class InvalidType < StandardError; end @@ -11,7 +12,7 @@ class InvalidType < StandardError; end integer: ActiveModel::Type::Integer.new, decimal: ActiveModel::Type::Decimal.new, float: ActiveModel::Type::Float.new, - boolean: ActiveModel::Type::Boolean.new, + boolean: Kredis::Type::Boolean.new, datetime: Kredis::Type::DateTime.new, json: Kredis::Type::Json.new } diff --git a/test/types/flag_test.rb b/test/types/flag_test.rb index b1df179..6bd02db 100644 --- a/test/types/flag_test.rb +++ b/test/types/flag_test.rb @@ -1,4 +1,5 @@ require "test_helper" +require "active_support/core_ext/integer" class FlagTest < ActiveSupport::TestCase setup { @flag = Kredis.flag "myflag" } diff --git a/test/types/scalar_test.rb b/test/types/scalar_test.rb index 29eacca..473ae3c 100644 --- a/test/types/scalar_test.rb +++ b/test/types/scalar_test.rb @@ -38,6 +38,22 @@ class ScalarTest < ActiveSupport::TestCase assert_equal false, boolean.value end + test "boolean casting" do + boolean = Kredis.boolean "myscalar" + + boolean.value = true + assert_equal "1", boolean.get + + boolean.value = false + assert_equal "0", boolean.get + + boolean.set "true" + assert_equal true, boolean.value + + boolean.set "false" + assert_equal false, boolean.value + end + test "datetime" do datetime = Kredis.datetime "myscalar" datetime.value = 5.days.from_now.midnight