Sha256: b2cd9b27168e6e66c0595dc6fb0b53854037eb3a65565bd8e88802e230614413

Contents?: true

Size: 982 Bytes

Versions: 10

Compression:

Stored size: 982 Bytes

Contents

require "json"
require "active_model/type"
require "kredis/type/json"
require "kredis/type/datetime"

module Kredis::TypeCasting
  class InvalidType < StandardError; end

  TYPES = {
    string: ActiveModel::Type::String.new,
    integer: ActiveModel::Type::Integer.new,
    decimal: ActiveModel::Type::Decimal.new,
    float: ActiveModel::Type::Float.new,
    boolean: ActiveModel::Type::Boolean.new,
    datetime: Kredis::Type::DateTime.new,
    json: Kredis::Type::Json.new
  }

  def type_to_string(value, type)
    raise InvalidType if type && !TYPES.key?(type)

    TYPES[type || :string].serialize(value)
  end

  def string_to_type(value, type)
    raise InvalidType if type && !TYPES.key?(type)

    TYPES[type || :string].cast(value)
  end

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

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

Version data entries

10 entries across 10 versions & 1 rubygems

Version Path
kredis-1.5.0 lib/kredis/type_casting.rb
kredis-1.4.0 lib/kredis/type_casting.rb
kredis-1.3.0.1 lib/kredis/type_casting.rb
kredis-1.3.0 lib/kredis/type_casting.rb
kredis-1.2.0 lib/kredis/type_casting.rb
kredis-1.1.0 lib/kredis/type_casting.rb
kredis-1.0.1 lib/kredis/type_casting.rb
kredis-1.0.0 lib/kredis/type_casting.rb
kredis-0.4.0 lib/kredis/type_casting.rb
kredis-0.3.1 lib/kredis/type_casting.rb