Sha256: 494ce0295768afe25080ca7fc0632b0c41f5632c375bae3b4d03881c88c843bb

Contents?: true

Size: 853 Bytes

Versions: 7

Compression:

Stored size: 853 Bytes

Contents

# frozen_string_literal: true
require_relative "base_enum_mapper"

class ReeEnum::StringValueEnumMapper < ReeEnum::BaseEnumMapper
  contract(
    ReeEnum::Value,
    Kwargs[
      name: String,
      location: Nilor[String],
    ] => String
  )
  def serialize(value, name:, location: nil)
    value.value
  end

  contract(
    Any,
    Kwargs[
      name: String,
      location: Nilor[String],
    ] => ReeEnum::Value
  ).throws(ReeMapper::CoercionError)
  def cast(value, name:, location: nil)
    enum_value = case value
    when String
      @enum.get_values.by_value(value)
    when ReeEnum::Value
      @enum.get_values.each.find { _1 == value }
    end

    if enum_value.nil?
      raise ReeMapper::CoercionError.new("`#{name}` should be one of #{enum_inspection}, got `#{truncate(value.inspect)}`", location)
    end

    enum_value
  end
end

Version data entries

7 entries across 7 versions & 1 rubygems

Version Path
ree_lib-1.0.93 lib/ree_lib/packages/ree_enum/package/ree_enum/string_value_enum_mapper.rb
ree_lib-1.0.92 lib/ree_lib/packages/ree_enum/package/ree_enum/string_value_enum_mapper.rb
ree_lib-1.0.91 lib/ree_lib/packages/ree_enum/package/ree_enum/string_value_enum_mapper.rb
ree_lib-1.0.90 lib/ree_lib/packages/ree_enum/package/ree_enum/string_value_enum_mapper.rb
ree_lib-1.0.89 lib/ree_lib/packages/ree_enum/package/ree_enum/string_value_enum_mapper.rb
ree_lib-1.0.88 lib/ree_lib/packages/ree_enum/package/ree_enum/string_value_enum_mapper.rb
ree_lib-1.0.87 lib/ree_lib/packages/ree_enum/package/ree_enum/string_value_enum_mapper.rb