Tuesday, March 29, 2011

Category - Advanced

class StringCategory {
  static String camelize(String self) {
    def newName = self.split("_").collect() { 
      it.substring(0, 1).toUpperCase() + it.substring(1, it.length())
    }.join()
    
    newName[0..<1].toLowerCase() +  newName[1..-1]      
  }
  static Integer getPm(Integer self) {
      (self == 12 ? 12 : self + 12)
  }
  static Integer getAm(Integer self) {
      self == 12 ? 0 : self
  }
}

class SpeakCategory {
    static String shout(String self) {  // Method argument is String, so we can add shout() to String object.
        self.toUpperCase() + '!!'
    }
    static String whisper(String self, boolean veryQuiet = false, Integer a = 0) {
        "${veryQuiet ? 'sssssssh' : 'sssh'}.. $self $a"
    }
    static String army(String self) {
        "$self. Sir, yes sir!"
    }
}

use (StringCategory) {
    println 'Hi_there_fella'.camelize()
    println 12.am + ' o\'clock'
    println 2.pm + ' o\'clock'
}

use (SpeakCategory) {
    println "Pay attention".shout()
    println "Be vewy, vewy, quiet.".whisper()
    println "Be vewy, vewy, quiet.".whisper(true, 1)
    println "Groovy rocks".army()
}

// Or we can use the @Category annotation.
// implicit 'this', no 'self' arg passed in
@Category(String) 
class StreetTalk {
    String hiphop(Integer times = 1) {
        "Yo, yo, here we go! " * times + "${this}"
    }
}

use(StreetTalk) {
    println 'Groovy is dope!'.hiphop(2)
}

http://groovyconsole.appspot.com/script/448002

No comments:

Post a Comment