Skip to content

Commit

Permalink
Add #to_anchor String extension
Browse files Browse the repository at this point in the history
This will convert a string into an URL HREF anchor. Specifically, we anticipate using this for headings in GitHub markdown files to construct links to those headings.
  • Loading branch information
darronschall committed May 28, 2024
1 parent 739e63f commit 04f3ebf
Show file tree
Hide file tree
Showing 2 changed files with 29 additions and 0 deletions.
14 changes: 14 additions & 0 deletions lib/twirp/protoc_plugin/core_ext/string/to_anchor.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,14 @@
# frozen_string_literal: true

class String
# Converts the string to an acceptable URL anchor.
#
# Thw rules for GitHub markdown links are:
# - force lowercase
# - strip punctuation
# - replace spaces with dashes
# @return [String] the string converted to an acceptable URL anchor
def to_anchor
downcase.gsub(/[^a-z0-9_ -]/, "").tr(" ", "-")
end
end
15 changes: 15 additions & 0 deletions spec/core_ext/string/to_anchor_spec.rb
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
# frozen_string_literal: true

require "twirp/protoc_plugin/core_ext/string/to_anchor"

RSpec.describe String do
describe "#to_anchor" do
it "converts a string with brackets, numbers, and dates" do
expect("[1.1.1] - 2024-05-22".to_anchor).to eq("111---2024-05-22")
end

it "converts a string with mixed case and backticks" do
expect("Install the `protoc-gen-twirp_ruby` plugin gem".to_anchor).to eq("install-the-protoc-gen-twirp_ruby-plugin-gem")
end
end
end

0 comments on commit 04f3ebf

Please sign in to comment.