Skip to content

Commit

Permalink
Add helpers to get random ids (#292)
Browse files Browse the repository at this point in the history
Deterministic ones if the almond.ids.random Java property is "0" or
"false".
  • Loading branch information
alexarchambault committed Dec 17, 2018
1 parent ff61315 commit 8e11ef6
Show file tree
Hide file tree
Showing 2 changed files with 26 additions and 4 deletions.
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,7 @@ import java.nio.file.{Files, Path, Paths}
import java.util.UUID

import almond.api.JupyterApi
import almond.api.helpers.Display
import almond.channels.ConnectionParameters
import almond.internals._
import almond.interpreter._
Expand Down Expand Up @@ -539,7 +540,7 @@ final class ScalaInterpreter(
DisplayData.text(res0)
case Some(r) =>
val d = r.add(
DisplayData.text(res0).withId(UUID.randomUUID().toString),
DisplayData.text(res0).withId(Display.newId()),
variables
)
outputHandler match {
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,8 @@ package almond.api.helpers
import java.io.{BufferedInputStream, IOException}
import java.net.{URL, URLConnection}
import java.nio.file.{Files, Paths}
import java.util.{Base64, UUID}
import java.util.concurrent.atomic.AtomicInteger
import java.util.{Base64, Locale, UUID}

import almond.interpreter.api.DisplayData.ContentType
import almond.interpreter.api.{DisplayData, OutputHandler}
Expand All @@ -21,8 +22,28 @@ final class Display(id: String, contentType: String) {

object Display {

private def newId(): String =
UUID.randomUUID().toString
def useRandomIds(): Boolean =
sys.props
.get("almond.ids.random")
.forall(s => s == "1" || s.toLowerCase(Locale.ROOT) == "true")

private val idCounter = new AtomicInteger
private val divCounter = new AtomicInteger

def newId(): String =
if (useRandomIds())
UUID.randomUUID().toString
else
idCounter.incrementAndGet().toString

def newDiv(prefix: String = "data-"): String =
prefix + {
if (useRandomIds())
UUID.randomUUID().toString
else
divCounter.incrementAndGet().toString
}


def markdown(content: String)(implicit outputHandler: OutputHandler): Display = {
val id = newId()
Expand Down

0 comments on commit 8e11ef6

Please sign in to comment.