Skip to content

String#dashcase library, test, and demo #297

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Open
wants to merge 1 commit into
base: main
Choose a base branch
from
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
Expand Up @@ -14,3 +14,5 @@ Gemfile.lock
*.gem
.bundle/
vendor/
.ruby-version
.ruby-gemset
13 changes: 13 additions & 0 deletions demo/core/string/dashcase.md
Original file line number Diff line number Diff line change
@@ -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'
21 changes: 21 additions & 0 deletions lib/core/facets/string/dashcase.rb
Original file line number Diff line number Diff line change
@@ -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
21 changes: 21 additions & 0 deletions test/core/string/test_dashcase.rb
Original file line number Diff line number Diff line change
@@ -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