Last active
March 25, 2016 02:20
-
-
Save sarveshseri/f188a1a52ff966c63ea4 to your computer and use it in GitHub Desktop.
Unique Id generator for models in Scala applications
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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