Skip to content

Instantly share code, notes, and snippets.

@sarveshseri
Last active March 25, 2016 02:20
Show Gist options
  • Save sarveshseri/f188a1a52ff966c63ea4 to your computer and use it in GitHub Desktop.
Save sarveshseri/f188a1a52ff966c63ea4 to your computer and use it in GitHub Desktop.
Unique Id generator for models in Scala applications
import org.joda.time.DateTime
import scala.annotation.tailrec
import scala.util.Random
object RANStream {
val randomAlphaNumIterator = Random.alphanumeric.iterator
@tailrec
def getRandomString(length: Int, acc: String = ""): String = {
require(length >= 0, message = "length needs to be non-negative")
if (length == 0) acc
else getRandomString(length - 1, randomAlphaNumIterator.next().toString)
}
}
trait UiidGen {
val key: String
def generateUiid: String = {
val longTime = DateTime.now().getMillis()
val hexTime = longTime.toHexString
(key + "_" + hexTime + "_" + RANStream.getRandomString(20))
.substring(0, 32)
}
}
object MyModel extends UiidGen {
override val key: String = "MyModel"
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment