user3060126
user3060126

Reputation: 501

Rails Titleize with "(s)"

I'm titleizing all simple form field labels by default which is great and I figured out how to add an acronym to stay capitalized in the inflections initializer, which is cool! (So "USA" stays "USA" and doesn't become "Usa"). However, I am stuck on a punctuation issue.

"State(s)" becomes "State(S)" after going through titleization. And "State/s" also becomes "State/S".

Any idea how I can add an exception for cases like that so it doesn't capitalize that last "S"?

Upvotes: 0

Views: 227

Answers (1)

Lanny Bose
Lanny Bose

Reputation: 1857

You can take a look at the code for the Rails titleize method on github, and you'll see that the regular expression getting sent as a parameter to gsub is:

/\b(?<!['’`])[a-z]/

As written, gsub takes every matched character in the expression and capitalizes it.

A great resource to test Ruby regular expressions is rubular.com. You can paste in the regex (don't forget that it's already giving you the leading and trailing '/') and try different strings to see what matches.

Here's a quick test using the above regex. You'll see that not only does "Streetlight(S)" broken by ( get a second capital S, but "Feee-Ling" broken by - gets a capital L.

In this case, the key to your issue is the section within the regex:

['’`]

...which I would infer is being used to identify all manner of apostrophe to get possessives and contractions right. If you were to put ( inside the brackets, your problem will be fixed. Go try it in rubular. Watch the highlighting disappear!

I couldn't tell you for sure the ramifications of monkey patching the Rails method. But you could write your own!

def titleize_optional_plurals(word)
  humanize(underscore(word)).gsub(/\b(?<!['’`(])[a-z]/) { $&.capitalize }
end

Upvotes: 2

Related Questions