Skip to content

Instantly share code, notes, and snippets.

@teigen
Last active December 19, 2015 00:00
Show Gist options
  • Save teigen/5865923 to your computer and use it in GitHub Desktop.
Save teigen/5865923 to your computer and use it in GitHub Desktop.
uri string interpolator
scala> import UriString._
import UriString._
scala> val a = "world"
a: String = world
scala> uri"hello/$a"
res3: String = hello/world
scala> val b = "http://"
b: String = http://
scala> uri"http://$b"
res4: String = http://http%3A%2F%2F
object UriString {
private val unreserved = {
val alphanum = (('a' to 'z') ++ ('A' to 'Z') ++ ('0' to '9')).toSet
val mark = Set('-', '_', '.', '!', '~', '*', '\'', '(', ')')
alphanum ++ mark
}
implicit class UriContext(val sc:StringContext) extends AnyVal {
def uri(args:String*) = {
val strings = sc.parts.iterator
val expressions = args.iterator
val sb = new StringBuffer(strings.next())
while(strings.hasNext){
for(c <- expressions.next()){
if(unreserved(c))
sb.append(c)
else for(b <- c.toString.getBytes("UTF-8")){
sb.append("%")
sb.append("%02X".format(b))
}
}
sb.append(strings.next())
}
sb.toString
}
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment