Posted By

fuzzylollipop on 10/06/09


Tagged

truncate metaclass metaprogramming


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

fuzzylollipop
laurenceosx
sfhynx


Adding a truncate method to a String in Groovy


 / Published in: Groovy
 

this truncates a string to a provided length and adds "..." to the end to show that it was truncated.

  1. // this adds a "truncate(#)" method to String and GString
  2. String.metaClass.truncate = {len ->
  3. if (delegate == null) {return ''}
  4. if (delegate.length() > len) {return delegate[0..(len - 4)] + '...'}
  5. return delegate
  6. }

Report this snippet  

You need to login to post a comment.