casualjim
8/22/2011 - 12:28 AM

core_extensions.scala

  object BackchatString {
    /**
     * Remove non-latin signs from text regular expression
     */
    val NON_LATIN = """[^A-Za-z0-9\-\.]""".r

    /**
     * Remove whitespace regular expression
     */
    val WHITESPACE = """[\s]""".r

    /**
     * Remove apostrophe regular expression
     */
    val APOSTROPHE = """['`]""".r

    /**
     * Remove double underscores regular epxression
     */
    val DOUBLE_UNDERSCORES = """(_|-)+""".r

    /**
     * Match at-sign regular expression
     */
    val AT_SIGN = """\s*@\s*""".r

    /**
     * Match Ampersand regular expression
     */
    val AMPERSAND = """\s*&\s*""".r

    /**
     * Match leading and trailing underscore regular expression
     */
    val LEAD_TRAIL_UNDERSCORE = """\A[_\.]+|[_\.]+\z""".r

    /**
     * Creates a slug from a given string. This can be used as a url
     *
     * @param nameValue the string to make a slug from
     */
    private def slugify(nameValue: String): String = {
      if (nameValue != null || nameValue.trim.length > 0) {
        val normalized = Normalizer.normalize(nameValue, Normalizer.NFD)
        val noApos = APOSTROPHE.replaceAllIn(normalized, "")
        val noAtSign = AT_SIGN.replaceAllIn(noApos, "at")
        val noAmper = AMPERSAND.replaceAllIn(noAtSign, "and")
        val noWhite = WHITESPACE.replaceAllIn(noAmper, "-")
        val almostThere = NON_LATIN.replaceAllIn(noWhite, "-")
        val singleUnderscored = DOUBLE_UNDERSCORES.replaceAllIn(almostThere, "-")
        val slug = LEAD_TRAIL_UNDERSCORE.replaceAllIn(singleUnderscored, "")

        slug.toLowerCase(Locale.ENGLISH)
      } else nameValue
    }


  }

  class BackchatString(s: String) {

    import BackchatString._
    def asSlug = slugify(s)


  }