Fixed and updated for advanced parse with json and add provider for exchange rate for money config

This commit is contained in:
Sambo Chea 2021-02-08 14:50:31 +07:00
parent faf80ba967
commit 36599b5fb5
3 changed files with 47 additions and 11 deletions

View File

@ -50,9 +50,14 @@ object MoneyConfig {
val rates = config.split(getProperties().deliSplit) val rates = config.split(getProperties().deliSplit)
rates.map { i -> rates.map { i ->
val temp = i.split(getProperties().deliEqual) val temp = i
// remove the quote from string
.replace("\"", "")
.split(getProperties().deliEqual)
if (temp.size == 2) { if (temp.size == 2) {
val currency = temp[0].toUpperCase().trim() val currency = temp[0]
.toUpperCase()
.trim()
val value = temp[1].toDouble() val value = temp[1].toDouble()
if (MoneyConfig.config.containsKey(currency)) { if (MoneyConfig.config.containsKey(currency)) {
MoneyConfig.config.replace(currency, value) MoneyConfig.config.replace(currency, value)
@ -74,6 +79,29 @@ object MoneyConfig {
} }
} }
fun appendRate(provider: MoneyExchangeProvider) = apply {
val currency = provider.getCurrency()
val rate = provider.getRate()
this.appendRate(currency, rate)
}
/**
* Json Format must be, example below
*
* {
* "USD": 1,
* "EUR": 0.99,
* "...": ...
* }
*/
fun fromJson(configJson: String, clearAllStates: Boolean = false) {
val transformValues = configJson
.removePrefix("{")
.removeSuffix("}")
parse(transformValues, clearAllStates)
}
// all currencies with its rate // all currencies with its rate
fun getConfig() = config fun getConfig() = config

View File

@ -1,5 +1,6 @@
package com.cubetiqs.money package com.cubetiqs.money
interface MoneyExchangeProvider { interface MoneyExchangeProvider {
fun getRate(currency: StdMoney.Currency): Double fun getCurrency(): String
fun getRate(): Double
} }

View File

@ -12,16 +12,15 @@ class MoneyTests {
// .setDeliSplit(',') // .setDeliSplit(',')
// .build() // .build()
val properties = buildMoneyConfigProperties {
setDeliEqual(':')
setDeliSplit(',')
}
applyMoneyConfig { applyMoneyConfig {
setProperties(properties) setProperties(buildMoneyConfigProperties {
setDeliEqual(':')
setDeliSplit(',')
})
// parse("USD:1,KHR:4000") // parse("USD:1,KHR:4000")
appendRate("usd", 1.0) // appendRate("usd", 1.0)
appendRate("khr", 4000.0) // appendRate("khr", 4000.0)
fromJson(MyBatchRates.getJsonRates())
} }
// Is valid for money config? // Is valid for money config?
@ -33,4 +32,12 @@ class MoneyTests {
// Is correct exchange? // Is correct exchange?
Assert.assertEquals(8000.0, moneyKhr.getMoneyValue(), 0.0) Assert.assertEquals(8000.0, moneyKhr.getMoneyValue(), 0.0)
} }
object MyBatchRates {
fun getJsonRates(): String {
return """
{"USD": 1.0,"KHR": 4000.0}
""".trimIndent()
}
}
} }