5000164 is here

設定ファイルを Scala で書く

Published 2018.5.26 by 菅原 浩

背景

目的

やり方

ディレクトリ構成

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
.
├── build.sbt
└── src
    └── main
        ├── resources
        │   ├── Settings.scala
        │   └── SettingsSample.scala
        └── scala
            ├── infrastructure
            │   └── Settings.scala
            └── interfaces
                └── Application.scala

具体的なコード

依存関係を解決

build.sbt

1
libraryDependencies += "org.scala-lang" % "scala-compiler" % scalaVersion.value

設定を Eval する

infrastructure/Settings.scala

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
package infrastructure

import scala.io.Source
import scala.reflect.runtime.{currentMirror, universe}
import scala.tools.reflect.ToolBox

object Settings {
  val toolbox: ToolBox[universe.type] = currentMirror.mkToolBox()
  val settings: SettingsType = toolbox.eval(toolbox.parse(Source.fromResource("Settings.scala").mkString)).asInstanceOf[SettingsType]
}

trait SettingsType {
  val hoge: String
  val foo: Int
}

設定を書く

resources/Settings.scala

1
2
3
4
5
6
import infrastructure.SettingsType

new SettingsType {
    override val hoge = "hogehoge"
    override val foo = 1
}

設定のサンプルを書く

resources/SettingsSample.scala

1
2
3
4
5
6
import infrastructure.SettingsType

new SettingsType {
    override val hoge = ""
    override val foo = 0
}

設定がリポジトリに含まれないようにする

.gitignore

1
src/main/resources/Settings.scala

使い方

interfaces/Application.scala

1
2
3
4
5
6
7
8
package interfaces

import infrastructure.Settings.settings

object Application extends App {
  println(settings.hoge)
  println(settings.foo)
}

現時点での問題点

参考