Module: Kredis::TypeCasting

Included in:
Kredis
Defined in:
lib/kredis/type_casting.rb

Defined Under Namespace

Classes: InvalidType

Constant Summary collapse

VALID_TYPES =
%i[ string integer decimal float boolean datetime json ]

Instance Method Summary collapse

Instance Method Details

#string_to_type(value, type) ⇒ Object

Raises:



27
28
29
30
31
32
33
34
35
36
37
38
39
# File 'lib/kredis/type_casting.rb', line 27

def string_to_type(value, type)
  raise InvalidType if type && !type.in?(VALID_TYPES)

  case type
  when nil, :string then value
  when :integer     then value.to_i
  when :decimal     then value.to_d
  when :float       then value.to_f
  when :boolean     then value == "t" ? true : false
  when :datetime    then Time.at(value.to_i)
  when :json        then JSON.load(value)
  end if value.present?
end

#strings_to_types(values, type) ⇒ Object



45
46
47
# File 'lib/kredis/type_casting.rb', line 45

def strings_to_types(values, type)
  Array(values).flatten.map { |value| string_to_type(value, type) }
end

#type_to_string(value) ⇒ Object



6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
# File 'lib/kredis/type_casting.rb', line 6

def type_to_string(value)
  case value
  when nil
    ""
  when Integer
    value.to_s
  when BigDecimal
    value.to_d
  when Float
    value.to_s
  when TrueClass, FalseClass
    value ? "t" : "f"
  when Time, DateTime, ActiveSupport::TimeWithZone
    value.to_f
  when Hash
    JSON.dump(value)
  else
    value
  end
end

#types_to_strings(values) ⇒ Object



41
42
43
# File 'lib/kredis/type_casting.rb', line 41

def types_to_strings(values)
  Array(values).flatten.map { |value| type_to_string(value) }
end