DynamicVariables for custom objects

64 views
Skip to first unread message

null

unread,
Nov 1, 2011, 2:53:22 AM11/1/11
to scalatra-user
I've recently started looking into scalatra (in fact, scala in
general) and among many other things, I really like the usage of
DynamicVariables for scoping access to the current request and
response objects.

I have a similar need for scoping a custom object of mine and I have
implemented a trait for it as such:

trait MyObjSupport extends ScalatraKernel {
override def executeRoutes() {
_myobj.withValue(new MyObj) {
super.executeRoutes()
}
}

implicit def myobj = _myobj value

protected val _myobj = new DynamicVariable[MyObj](null)
}

I subsequently mixin MyObjSupport into my servlets that need access to
myobj.

I was wondering if someone can comment on the merits / demerits of
this approach. And if there are any better alternatives to this one
for scoping custom objects.

Thanks,
Keyur

Ivan Porto Carerro

unread,
Nov 1, 2011, 3:31:50 AM11/1/11
to scalat...@googlegroups.com
Hi,

You can also use this approach: 

before() {
  request("myObjKey") = new MyObj
}

def myObj = request("myObjKey").asInstanceOf[MyObj] // AnyRef

By making your myObj a request attribute it's automatically scoped to the request.

null

unread,
Nov 1, 2011, 3:49:57 AM11/1/11
to scalatra-user
Thanks. The one you suggested is perhaps a low-cost solution compared
to mine - will go with yours.

Wondering if either has any performance benefits over the other -
probably should not worry about that one just yet.

== Keyur

Ross A. Baker

unread,
Nov 1, 2011, 10:20:50 AM11/1/11
to scalat...@googlegroups.com
I like to make the decision based on intent. If the intent is to
scope something to a thread, use a DynamicVariable. If the intent is
to scope something to a request, use a request attribute. These
scopes work out to be the same in the standard servlet model, but
barring major performance implications (I've seen none), it's best to
just say what you mean. For me, that's usually a request attribute.

--
Ross A. Baker
ba...@alumni.indiana.edu
Indianapolis, IN, USA

Reply all
Reply to author
Forward
0 new messages