Skip to content
This repository has been archived by the owner on Sep 15, 2024. It is now read-only.

Typesafe injector #79

Merged
merged 2 commits into from
May 8, 2016
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 26 additions & 2 deletions src/main/scala/com/greencatsoft/angularjs/core/Injector.scala
Original file line number Diff line number Diff line change
@@ -1,11 +1,35 @@
package com.greencatsoft.angularjs.core

import com.greencatsoft.angularjs.injectable
import com.greencatsoft.angularjs.{injectable, internal}
import com.greencatsoft.angularjs.internal.ServiceProxy

import scala.language.experimental.macros
import scala.reflect.macros.blackbox.Context
import scala.scalajs.js

@injectable("$injector")
@js.native
trait Injector extends js.Object {
def get(name: String): js.Object = js.native
def get[A](name: String): A = js.native
}

/** Supports easy, type safe injection of types annotated with `@injectable`.
*
* See example:
* {{{
* implicit val injector = Angular.injector("ng", "myModule")
* val compile = Injector.get[Compile]
* val rootScope = Injector.get[RootScope]
* }}}
*/
object Injector {
/** Gets an instance of the specified type from the provided injector.
*
* Fails at compile time, if the type isn't annotated with `@injectable`.
*
* @param injector the injector to retrieve the type from
* @tparam A the type to return an instance of
* @return instance of the specified type provided by the injector
*/
def get[A](implicit injector: Injector): A = macro internal.Injector.get[A]
}
18 changes: 18 additions & 0 deletions src/main/scala/com/greencatsoft/angularjs/internal/Injector.scala
Original file line number Diff line number Diff line change
@@ -0,0 +1,18 @@
package com.greencatsoft.angularjs.internal

import com.greencatsoft.angularjs.core

import scala.reflect.macros.blackbox.Context

private[angularjs] object Injector {

def get[A](c: Context)(injector: c.Expr[core.Injector])(implicit tag: c.WeakTypeTag[A]): c.Expr[A] = {
import c.universe._

val name = ServiceProxy.identifierFromType(c)(tag.tpe) getOrElse {
c.abort(c.enclosingPosition, s"The specified type '${tag.tpe}' does not have @injectable annotation.")
}
val nameExpr = c.Expr[String](q"$name")
reify { injector.splice.get[A](nameExpr.splice) }
}
}