Skip to content

Chaining refined string operation #1080

@aurrelhebert

Description

@aurrelhebert

Context

Hi, I would like to use REFINED to validate some custom input string I have. For some of the string, I would like to chain existing refined string operation as start_with and uuid.

Exemple

The input string I have looks like random_VALID_UUID. At the moment I write a custom refined type as:

final case class PrefixedUUID[S](prefix: S)

object PrefixedUUID {

  implicit def prefixedUUIDValidate[S <: String](
      implicit
      prefix: Witness.Aux[S]
    ): Validate.Plain[String, PrefixedUUID[S]] = {
    Validate.fromPartial(
      s => {
        if (s.startsWith(prefix.value)) {
          val uuid: String = s.stripPrefix(prefix.value)
          require(java.util.UUID.fromString(uuid).toString == uuid.toLowerCase)
        } else {
          throw new Exception("Not a valid UUID")
        }
      },
      s"""PrefixedUUID("${prefix.value}")""",
      PrefixedUUID(prefix.value)
    )
  }
}

Is it the best approach to do it? Can I do it in a more generic way (chaining native refined operation)? If not, maybe can you lead me on how I can contribute a generic way to do it for the core refined library, if you are interested?

Thanks,

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions