Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Added json string interpolation #132

Closed
wants to merge 4 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions src/main/scala/argonaut/Argonaut.scala
Original file line number Diff line number Diff line change
Expand Up @@ -16,6 +16,7 @@ EncodeJsons with
HCursors with
Jsons with
JsonIdentitys with
JsonInterpolator with
JsonObjects with
PrettyParamss with
StringWraps
22 changes: 22 additions & 0 deletions src/main/scala/argonaut/JsonInterpolator.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,22 @@
package argonaut

import scalaz.\/

trait JsonInterpolator {

implicit class JsonHelper(sc: StringContext) {
def json(expressions: Any*): String \/ Json = {
val stringsItr = sc.parts.iterator
val expressionsItr = expressions.iterator

// Combine string parts, starting with fencepost
var buffer = new StringBuffer(stringsItr.next)
while (stringsItr.hasNext) {
buffer.append(expressionsItr.next)
buffer.append(stringsItr.next)
}
Parse.parse(buffer.toString)
}
}

}
38 changes: 38 additions & 0 deletions src/test/scala/argonaut/JsonInterpolatorSpecification.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,38 @@
package argonaut

import argonaut._, Argonaut._
import scalaz._, Scalaz._
import org.specs2._
import org.specs2.specification._

object JsonInterpolatorSpecification extends Specification {
val constructedJson =
Json(
"name" := "fred",
"age" := 23,
"wallet" := List(
Json("value" := 100),
Json("value" := 10),
Json("value" := 50)
)
)

val age = 23
val interpolatedJson =
json"""
{
"name": "fred",
"age": $age,
"wallet": [
{ "value": 100 },
{ "value": 10 },
{ "value": 50 }
]
}
""".getOrElse(throw new Exception())

def is = s2"""
Constructed Json matches interpolated Json
${constructedJson must_== interpolatedJson}
"""
}