New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Typesafe injector #79

Merged
merged 2 commits into from May 8, 2016
Jump to file or symbol
Failed to load files and symbols.
+44 −2
Diff settings

Always

Just for now

@@ -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]
}
@@ -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) }
}
}