Skip to content

Commit

Permalink
#157 Add open initializer function to Entity
Browse files Browse the repository at this point in the history
EntityClass.new {} functions made open to support overriding
  • Loading branch information
Tapac committed Sep 13, 2017
1 parent 5ffe7fd commit eac1099
Show file tree
Hide file tree
Showing 2 changed files with 27 additions and 2 deletions.
4 changes: 2 additions & 2 deletions src/main/kotlin/org/jetbrains/exposed/dao/Entity.kt
Original file line number Diff line number Diff line change
Expand Up @@ -568,9 +568,9 @@ abstract class EntityClass<ID : Any, out T: Entity<ID>>(val table: IdTable<ID>,
}
}

fun new(init: T.() -> Unit) = new(null, init)
open fun new(init: T.() -> Unit) = new(null, init)

fun new(id: ID?, init: T.() -> Unit): T {
open fun new(id: ID?, init: T.() -> Unit): T {
val entityId = EntityID(id, table)
val prototype: T = createInstance(entityId, null)
prototype.klass = this
Expand Down
Original file line number Diff line number Diff line change
Expand Up @@ -41,14 +41,24 @@ object EntityTestsData {
object NotAutoIntIdTable : IdTable<Int>("") {
override val id: Column<EntityID<Int>> = integer("id").entityId()
val b1 = bool("b1")
val defaultedInt = integer("i1")
}

class NotAutoEntity(id: EntityID<Int>) : Entity<Int>(id) {
var b1 by NotAutoIntIdTable.b1
var defaultedInNew by NotAutoIntIdTable.defaultedInt

companion object : EntityClass<Int, NotAutoEntity>(NotAutoIntIdTable) {
val lastId = AtomicInteger(0)
internal const val defaultInt = 42
fun new(b: Boolean) = new(lastId.incrementAndGet()) { b1 = b }

override fun new(id: Int?, init: NotAutoEntity.() -> Unit): NotAutoEntity {
return super.new(id ?: lastId.incrementAndGet()) {
defaultedInNew = defaultInt
init()
}
}
}
}

Expand Down Expand Up @@ -121,6 +131,21 @@ class EntityTests: DatabaseTestsBase() {
}
}

@Test fun testDefaultsWithOverrideNew() {
withTables(EntityTestsData.NotAutoIntIdTable) {
val entity1 = EntityTestsData.NotAutoEntity.new(true)
assertEquals(true, entity1.b1)
assertEquals(EntityTestsData.NotAutoEntity.defaultInt, entity1.defaultedInNew)

val entity2 = EntityTestsData.NotAutoEntity.new {
b1 = false
defaultedInNew = 1
}
assertEquals(false, entity2.b1)
assertEquals(1, entity2.defaultedInNew)
}
}

@Test fun testBlobField() {
withTables(EntityTestsData.YTable) {
val y1 = EntityTestsData.YEntity.new {
Expand Down

0 comments on commit eac1099

Please sign in to comment.