Skip to content

Instantly share code, notes, and snippets.

@p3t0r
Created April 28, 2011 19:25
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save p3t0r/947112 to your computer and use it in GitHub Desktop.
Save p3t0r/947112 to your computer and use it in GitHub Desktop.
example of encoding parameters in the methodname using the Dynamic trait
package com.log4.methodmissing
import java.lang.Integer
class ParameterInMethodNameExample extends Dynamic {
def find(by:String, value:String) = "select from users where %s = '%s'".format(by, value)
def find(by:String, value:Integer) = "select from users where %s = %s".format(by, value)
def delete(by:String, value:String) = "delete from users where %s = '%s'".format(by, value)
def delete(by:String, value:Integer) = "delete from users where %s = %s".format(by, value)
def applyDynamic(methodName: String)(args: Any*) = {
WordUtils.decamelize(methodName) match {
case x :: xs if xs.contains("by") => {
val invokeArgs = List(xs.last, args.head)
val result = getClass.getMethod(x, invokeArgs.map(_.asInstanceOf[AnyRef].getClass): _*) // self-reflection
.invoke(this, invokeArgs.map(_.asInstanceOf[AnyRef]) : _*)
println(result)
}
case _ => throw new UnsupportedOperationException
}
}
}
object ParameterInMethodNameExample {
def main(args: Array[String]) {
val inMethodNameExample = new ParameterInMethodNameExample
inMethodNameExample.findByName("peter") // <-- calls find("name", "peter")
inMethodNameExample.findById(1234) // <-- calls find("id", 1234)
inMethodNameExample.deleteById(123345) // <-- calls delete("id", 123345)
inMethodNameExample.deleteWhereId(123) // <-- doesn't match pattern, throw USOE
}
}
object WordUtils {
def decamelize(s: String) = { // from http://stackoverflow.com/questions/2559759
s.replaceAll("%s|%s|%s".format("(?<=[A-Z])(?=[A-Z][a-z])", "(?<=[^A-Z])(?=[A-Z])", "(?<=[A-Za-z])(?=[^A-Za-z])"), ",").toLowerCase.split(",").toList
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment