Skip to content

Commit

Permalink
added docu for string based scripts
Browse files Browse the repository at this point in the history
  • Loading branch information
Simon committed May 8, 2018
1 parent 1134673 commit 80169d4
Show file tree
Hide file tree
Showing 2 changed files with 28 additions and 3 deletions.
21 changes: 18 additions & 3 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,8 @@ It's enabled by [JSR 223](https://www.jcp.org/en/jsr/detail?id=223) (Java Script
### Running a script from file system

A simple usage example for KtsRunner can be described as follows:
The definition of a class is placed in a `.kts file, which is loaded into a normal Kotlin program.
The declaration of a class is placed in a `.kts file, which is supposed to be loaded into a normal Kotlin program so that it
can be processed further.

1. The example class
```kotlin
Expand All @@ -27,10 +28,24 @@ ClassFromScript("I was created in kts")

```kotlin
val scriptReader = Files.newBufferedReader(Paths.get("path/classDeclaration.kts"))
val loadedObj = KtsObjectLoader().load<ClassFromScript>(scriptReader)
val loadedObj: ClassFromScript = KtsObjectLoader().load<ClassFromScript>(scriptReader)
println(loadedObj.x)
// >> I was created in kts
```

As shown, the `KtsObjectLoader` class can be used for executing a `.kts` script and return its result. The example shows a script that creates an instance of the `ClassFromScript` type that is loaded via ``KtsObjectLoader`` and then processed in the regular program.

### Executing scripts directly

The `KtsObjectLoader` also allows the evaluation of simple `String` based scripts:

```kotlin
val scriptContent = "5 + 10"
val fromScript: Int = KtsObjectLoader().load<Int>(scriptContent))
println(fromScript)
// >> 15
```

As shown, the `KtsObjectLoader` class can be used for loading an object from a `.kts` file. Currently, the library only supports single entities coming from the script.

## Getting Started

Expand Down
10 changes: 10 additions & 0 deletions src/test/kotlin/de/swirtz/ktsobjectloader/KtsObjectLoaderTest.kt
Original file line number Diff line number Diff line change
Expand Up @@ -43,6 +43,16 @@ class KtsObjectLoaderTest {
}
}

@Test
fun `expression from script`() {
val scriptContent = "5 + 10"

println(scriptContent)
assertEquals(15, KtsObjectLoader().load(scriptContent))
}



@Test
fun `class loaded from script`() {
val scriptContent = Files.readAllBytes(Paths.get("src/test/resources/testscript.kts"))?.let {
Expand Down

0 comments on commit 80169d4

Please sign in to comment.