Groovy web console

subscribe to the feed Subscribe
to this
site
Last fix of the Date DSL, it's shorter and a bit more lenient (via #groovywebconsole)
tweet this snippet Tweet
this
script

Last fix of the Date DSL, it's shorter and a bit more lenient

Published 8 years ago by Tim Yates with tags Date Calendar DSL
Actions  ➤ Edit in console Back to console Show/hide line numbers View recent scripts
import java.util.Calendar as C
class DateDSLDelegate {
  static days = [ 'sunday':C.SUNDAY, 'monday':C.MONDAY, 'tuesday':C.TUESDAY, 'wednesday':C.WEDNESDAY, 'thursday':C.THURSDAY, 'friday':C.FRIDAY, 'saturday':C.SATURDAY ]
  static months = [ 'january', 'february', 'march', 'april', 'may', 'june', 'july', 'august', 'september', 'october', 'november', 'december' ]
  def handler = [:]
  def methodMissing( String name, args ) {
    if( name in months )     {  handler.month = months.indexOf( name ) ; call( args ) }
    else if( days[ name ] )  { handler.day = days[ name ] ; call( args ) }
    else if( name == 'day' ) { handler.day = days.values() ; call( args ) }
    else if( name == 'in' )  { call( args ) }
    else throw new MissingMethodException( name, delegate.class, args )
  }
  def call( args ) {
    def cal = C.getInstance()
    cal.clear()
     def vals = []
    def monthSet = 'month' in handler.keySet()
    args.each { year ->
      cal.set( year, monthSet ? handler.month : C.JANUARY, 1 )
      def days = []
      while( monthSet ? cal.get( C.MONTH ) == handler.month : cal.get( C.YEAR ) == year ) {
        if( cal.get( C.DAY_OF_WEEK ) in handler.day ) {
          days << cal.getTime()
        }
         cal.add( C.DAY_OF_YEAR, 1 )
      }
      if( 'offset' in handler.keySet() ) { vals << days[ handler.offset ] } else { vals.addAll( days ) }
    }
    vals.size() == 1 ? vals[ 0 ] : vals
  }
  def propertyMissing( name ) {
    if( days[ name ] )        { handler.day = days[ name ] ; this }
    else if( name == 'day' )  { handler.day = days.values() ; this }
    else if( name == 'in' )   { this }
    else                      { name  }
  }
}
class DateDSL {
  def first()     { new DateDSLDelegate( handler:[offset: 0] ) }
  def last()      { new DateDSLDelegate( handler:[offset:-1] ) }
  def every()     { new DateDSLDelegate() }
  def propertyMissing( name ) {
    if( metaClass.respondsTo( this, name ) ) {  this."$name"() }
    else                                     { name  }
  }
}

def dsl = new DateDSL()
dsl.with {
  println first.monday.in.march( 2009, 2010 )
  println first.monday.march( 2009, 2010 )
  println every.wednesday.in( 2009 )
  println every.wednesday( 2009 )
  println last.friday.in.october( 2009 )
  println last.day.in.december( 2009 )
  println first.day.in( 2010 )
  println every.wednesday.in.october( 2009 )
  assert last.day( 2009 ) == last.day.in.december( 2009 )
  assert last.day.in( 2009 ) + 1 == first.day.in.january( 2010 )
}