Skip to content

Instantly share code, notes, and snippets.

@yamashiro
Created May 10, 2012 05:39
Show Gist options
  • Save yamashiro/2651257 to your computer and use it in GitHub Desktop.
Save yamashiro/2651257 to your computer and use it in GitHub Desktop.
ScalaでDIというかServiceLocator的な名状しがたい何か
trait ApiInjector {
var twitter : TwitterApi = new TwitterApiImpl;
//他にもいろいろなサービス
}
trait TwitterApi {
def publicTimeLines : List[String]
//他にも沢山の api
}
class TwitterApiImpl extends TwitterApi {
def publicTimeLines : List[String] = {
//Twitter API つかってごにょごにょするはず
List("本当は", "リアルに", "public", "timeline", "取得する")
}
}
class TwitterClient extends ApiInjector {
def indexedPublicTimeLine : List[String] = {
twitter.publicTimeLines.zipWithIndex
.map{ case (s, i) => (i + 1) + " " + s}
}
}
import org.specs2.mutable._
trait TestApiInjector extends ApiInjector {
twitter = new TwitterApi {
def publicTimeLines = {
List ("dummy", "public", "timeline")
}
}
}
class TwitterClientTest extends Specification {
"Twitter Api Client" should {
val client = new TwitterClient with TestApiInjector
val indexedPublicTimeLine = client.indexedPublicTimeLine
"indexedPublicTimeLine return size " in {
indexedPublicTimeLine.size must_== 3
}
"indexedPublicTimeLine return indexedLine" in {
indexedPublicTimeLine(0) must_== "1 dummy"
}
}
}
@seratch
Copy link

seratch commented May 10, 2012

override val とかできるので var じゃなくても差し替えられますよ。

trait ApiInjector {
  val twitter : TwitterApi = new TwitterApiImpl
}

trait TestApiInjector extends ApiInjector {
  override val twitter = new TwitterApi {
    def publicTimeLines = {
      List ("dummy", "public", "timeline")
    }
  }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment