Upgrade to Pro — share decks privately, control downloads, hide ads and more …

DSL Builders

DSL Builders

A quick introductions into DSLs/Typesafe builders with Kotlin.
by Gesh Markov
presented on October 26, 2017 at @Magicline

Kotlin User Group Hamburg

October 26, 2017
Tweet

More Decks by Kotlin User Group Hamburg

Other Decks in Programming

Transcript

  1. public class MockResponseBuilder { private final MockResponse response = new

    MockResponse(); public MockResponseBuilder withAsset(String asset) { response.addHeader("Content-Type", "application/json"); try (InputStream in = InstrumentationRegistry.getContext().getAssets().open(asset)){ response.setBody(new Buffer().readFrom(in)); } return this; }
  2. public class MockResponseBuilder { private final MockResponse response = new

    MockResponse(); public MockResponseBuilder withAsset(String asset) { response.addHeader("Content-Type", "application/json"); try (InputStream in = InstrumentationRegistry.getContext().getAssets().open(asset)){ response.setBody(new Buffer().readFrom(in)); } return this; } new MockResponseBuilder.withAsset(“my-awesome.json”).build()
  3. public class MockResponseBuilder { private final MockResponse response = new

    MockResponse() ; public MockResponseBuilder withAsset(String asset) { response.addHeader( "Content-Type" , "application/json" ); try (InputStream in = InstrumentationRegistry. getContext().getAssets().open(asset)){ response.setBody( new Buffer().readFrom(in)) ; } return this; } new MockResponseBuilder.withAsset(“my-awesome.json”) .setResponseCode(404) .addHeader(“foo”, “bar”).build()
  4. fun MockResponse.body(init: Buffer.() -> Unit) { val buffer = Buffer()

    buffer.init() body = buffer } fun Buffer.readFromTestAsset(responseJsonPath: String) { InstrumentationRegistry.context.assets.open(responseJsonPath).use { readFrom(it) } }
  5. fun mockResponse(init: MockResponse.() -> Unit): MockResponse { val response =

    MockResponse() response.init() return response } mockResponse { body { readFromTestAsset(“my-awesome.json”) } }
  6. fun MockResponse.addHeaders(vararg pairs: Pair<String, String>) { pairs.forEach { addHeader(it.first, it.second)

    } } mockResponse { body { readFromTestAsset(“my-awesome.json”) } statusCode = 404 addHeaders(“foo” to “bar”, “baz” to “qux”) }
  7. new MockResponseBuilder.withAsset(“my-awesome.json”).build() .setResponseCode(404) .addHeader(“foo”, “bar”) .addHeader(“baz”, “qux”).build(); mockResponse { body

    { readFromTestAsset(“my-awesome.json”) } statusCode = 404 addHeaders(“foo” to “bar”, “baz” to “qux”) }