int item = Math.random() * 100000 def doCode = { return 'hi' } Map $_ = [a: 1, b: ['c d': [z: item, doit: doCode]]] use (UtilCategory) { assert $_.dotPath() == [a: 1, b: ['c d': [z: item, doit: doCode]]] assert $_.dotPath('') == [a: 1, b: ['c d': [z: item, doit: doCode]]] assert $_.dotPath(null) == [a: 1, b: ['c d': [z: item, doit: doCode]]] assert $_.dotPath('a') == 1 assert $_.dotPath('b.c d.z') == item assert $_.dotPath('b/c d/z', '/') == item assert $_.dotPath('b.c d.doit')() == 'hi' assert $_.dotPath('b.c d.y') == null assert $_.dotPath('b.c d.z.z') == null assert $_.dotPath('b.c d.z.z.') == null assert 1.dotPath('toString') == null } //======================================== @Category(Object) class UtilCategory { def dotPath(String path = '', String delimiter = /\./) { Object self = this if (!path) return self try { return path.split(/$delimiter/).inject(self) { x, i-> x = x[i] } } catch (Exception ex) { return null } } }
Thursday, January 16, 2014
dotPath
Subscribe to:
Post Comments (Atom)
No comments:
Post a Comment