Permalink
Browse files

Snakify now handles abbreviations. Closes #381

  • Loading branch information...
1 parent 88bede6 commit 606ec2698a4985e5d37d52b5df4f8b1a7eda2fe3 @jeppenejsum jeppenejsum committed Mar 5, 2010
View
18 framework/lift-base/lift-util/src/main/scala/net/liftweb/util/StringHelpers.scala
@@ -77,20 +77,14 @@ trait StringHelpers {
/**
* Turn a string of format "FooBar" into snake case "foo_bar"
- *
+ *
+ * Note: snakify is not reversible, ie. in general the following will _not_ be true:
+ *
+ * s == camelify(snakify(s))
+ *
* @return the underscored string
*/
- def snakify(name : String) = {
- def loop(x : List[Char]) : List[Char] = x match {
- case c :: rest if (Character.isUpperCase(c)) => '_' :: Character.toLowerCase(c) :: loop(rest)
- case c :: rest => c :: loop(rest)
- case Nil => Nil
- }
- if (name.isEmpty)
- ""
- else
- (Character.toLowerCase(name.charAt(0)) :: loop(name.substring(1).toList)).mkString
- }
+ def snakify(name : String) = name.replaceAll("([A-Z]+)([A-Z][a-z])", "$1_$2").replaceAll("([a-z\\d])([A-Z])", "$1_$2").toLowerCase
/**
View
29 framework/lift-base/lift-util/src/test/scala/net/liftweb/util/StringHelpersSpec.scala
@@ -27,11 +27,34 @@ import _root_.org.specs.ScalaCheck
import common._
object StringHelpersSpec extends Specification with StringHelpers with StringGenerators with ScalaCheck {
- "The unCamelCase function" should {
- "Uncamel a name, replacing upper cases with underscores" in {
- forAllProp(camelCasedStrings)((name: String) => camelify(snakify(name)) == name) must pass
+ "The snakify function" should {
+ "replace upper case with underscore" in {
+ snakify("MyCamelCase") must_== "my_camel_case"
+ snakify("CamelCase") must_== "camel_case"
+ snakify("Camel") must_== "camel"
+ snakify("MyCamel12Case") must_== "my_camel12_case"
+ snakify("CamelCase12") must_== "camel_case12"
+ snakify("Camel12") must_== "camel12"
+ }
+
+ "not modify existing snake case strings" in {
+ snakify("my_snake_case") must_== "my_snake_case"
+ snakify("snake") must_== "snake"
+ }
+
+ "handle abbeviations" in {
+ snakify("HTML") must_== "html"
+ snakify("HTMLEditor") must_== "html_editor"
+ snakify("EditorTOC") must_== "editor_toc"
+ snakify("HTMLEditorTOC") must_== "html_editor_toc"
+
+ snakify("HTML5") must_== "html5"
+ snakify("HTML5Editor") must_== "html5_editor"
+ snakify("Editor2TOC") must_== "editor2_toc"
+ snakify("HTML5Editor2TOC") must_== "html5_editor2_toc"
}
}
+
"The camelify function" should {
"CamelCase a name which is underscored, removing each underscore and capitalizing the next letter" in {
def previousCharacterIsUnderscore(name: String, i: Int) = i > 1 && name.charAt(i - 1) == '_'

0 comments on commit 606ec26

Please sign in to comment.