Reputation: 7288
I'm currently building an accounting app, now I want to persist this "Period End Date" that is changeable. I believe we can use global variable, however I don't know how to do so. What I have tried so far is to create a variable in application.conf
like this application.date="2014/12/15"
.
Moreover, I'm not sure how to change the value using above approach . Is there any good approach for this problem ?
Upvotes: 4
Views: 3358
Reputation: 10884
A possible way to go is to use a Singeleton Object which is initialized in the Global.scala.
The Global Object has to go in the scala-root of the application or to be configured through application.conf
.
Singleton for shared Data
in app/shared/Shared.scala
(the name is free)
package shared
object Shared {
private var data: Int = 0
def setData(d: Int) : Unit = data = 0
def getData : Int = data
}
In application.conf
you can set the Global to be called on start of the application (you could also just put a file called Global.scala
in app, that would be used by default)
application.global= settings.Global
shared.initial = 42
In app/settings/Global.scala
object Global extends GlobalSettings {
override def onStart(app: Application) {
// Here I use typesafe config to get config data out of application conf
val cfg: Config = ConfigFactory.load()
val initialValue = cfg.getInt(shared.initial)
// set initial value for shared
Shared.setData(initialValue)
}
}
In Play code to get or set the shared data.
import shared.Shared
Shared.getData
Shared.setData( 8 )
Upvotes: 4