Last active
December 19, 2015 00:00
-
-
Save teigen/5865923 to your computer and use it in GitHub Desktop.
uri string interpolator
This file contains 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
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 |
This file contains 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
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