diff --git a/.gitignore b/.gitignore index 4fe5f5c1..40ff7af3 100644 --- a/.gitignore +++ b/.gitignore @@ -14,3 +14,5 @@ Gemfile.lock *.gem .bundle/ vendor/ +.ruby-version +.ruby-gemset diff --git a/demo/core/string/dashcase.md b/demo/core/string/dashcase.md new file mode 100644 index 00000000..3fe2fd64 --- /dev/null +++ b/demo/core/string/dashcase.md @@ -0,0 +1,13 @@ +## String#dashcase + + require 'facets/string/dashcase' + +Dashcase a string such that camelcase, underscores and spaces are +replaced by dashes. This is similar to {#underscore}, +but with dashes instead of underscores. + + 'my_name'.dashcase.assert == 'my-name' + + 'MyName'.dashcase.assert == 'my-name' + + 'URI'.dashcase.assert == 'uri' diff --git a/lib/core/facets/string/dashcase.rb b/lib/core/facets/string/dashcase.rb new file mode 100644 index 00000000..d2b04290 --- /dev/null +++ b/lib/core/facets/string/dashcase.rb @@ -0,0 +1,21 @@ +class String + + # Dashcase a string such that camelcase, underscores and spaces are + # replaced by dashes. This is similar to {#underscore}, + # but with dashes instead of underscores. + # + # "DashCase".dashcase #=> "dash-case" + # "Dash-Case".dashcase #=> "dash-case" + # "Dash Case".dashcase #=> "dash-case" + # "Dash - Case".dashcase #=> "dash-case" + + def dashcase + gsub(/([A-Z]+)([A-Z][a-z])/,'\1_\2'). + gsub(/([a-z\d])([A-Z])/,'\1_\2'). + tr('_', '-'). + gsub(/\s/, '-'). + gsub(/__+/, '-'). + downcase + end + +end diff --git a/test/core/string/test_dashcase.rb b/test/core/string/test_dashcase.rb new file mode 100644 index 00000000..71c06537 --- /dev/null +++ b/test/core/string/test_dashcase.rb @@ -0,0 +1,21 @@ +covers 'facets/string/dashcase' + +test_case String do + + method :dashcase do + + test "from camelcase" do + "DashCase".dashcase.assert == "dash-case" + end + + test "containing an underscore" do + "Dash_Case".dashcase.assert == "dash-case" + end + + test "containing spaces" do + "Dash Case".dashcase.assert == "dash-case" + end + + end + +end