Skip to content

Commit a686d2d

Browse files
committed
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.
1 parent 6e4f77c commit a686d2d

File tree

4 files changed

+31
-2
lines changed

4 files changed

+31
-2
lines changed

lib/kredis/type/boolean.rb

Lines changed: 11 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,11 @@
1+
# frozen_string_literal: true
2+
3+
module Kredis
4+
module Type
5+
class Boolean < ActiveModel::Type::Boolean
6+
def serialize(value)
7+
super ? 1 : 0
8+
end
9+
end
10+
end
11+
end

lib/kredis/type_casting.rb

Lines changed: 3 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,8 @@
11
require "json"
22
require "active_model/type"
3-
require "kredis/type/json"
3+
require "kredis/type/boolean"
44
require "kredis/type/datetime"
5+
require "kredis/type/json"
56

67
module Kredis::TypeCasting
78
class InvalidType < StandardError; end
@@ -11,7 +12,7 @@ class InvalidType < StandardError; end
1112
integer: ActiveModel::Type::Integer.new,
1213
decimal: ActiveModel::Type::Decimal.new,
1314
float: ActiveModel::Type::Float.new,
14-
boolean: ActiveModel::Type::Boolean.new,
15+
boolean: Kredis::Type::Boolean.new,
1516
datetime: Kredis::Type::DateTime.new,
1617
json: Kredis::Type::Json.new
1718
}

test/types/flag_test.rb

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,4 +1,5 @@
11
require "test_helper"
2+
require "active_support/core_ext/integer"
23

34
class FlagTest < ActiveSupport::TestCase
45
setup { @flag = Kredis.flag "myflag" }

test/types/scalar_test.rb

Lines changed: 16 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -38,6 +38,22 @@ class ScalarTest < ActiveSupport::TestCase
3838
assert_equal false, boolean.value
3939
end
4040

41+
test "boolean casting" do
42+
boolean = Kredis.boolean "myscalar"
43+
44+
boolean.value = true
45+
assert_equal "1", boolean.get
46+
47+
boolean.value = false
48+
assert_equal "0", boolean.get
49+
50+
boolean.set "true"
51+
assert_equal true, boolean.value
52+
53+
boolean.set "false"
54+
assert_equal false, boolean.value
55+
end
56+
4157
test "datetime" do
4258
datetime = Kredis.datetime "myscalar"
4359
datetime.value = 5.days.from_now.midnight

0 commit comments

Comments
 (0)