Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using titleize for acronym in Rails

I am defining some active records with acronyms. RvPark (Recreational Vehicle Park). When I titleize the class name, I get 'Rv Park'. It really should be 'RV Park'. Is there a good way to do this? Since this model shares code with other models, I need to create a generic solution, but I haven't been able to come up with one.

I did see a discussion on this, but there wasn't a solution that worked for me. any insight is appreciated.

https://rails.lighthouseapp.com/projects/8994/tickets/2944-titleize-doesnt-take-all-uppercase-words-into-account

like image 426
Jae Cho Avatar asked Mar 29 '11 00:03

Jae Cho


People also ask

What is capitalized and titleize in rails?

Capitalizes all the words and replaces some characters in the string to create a nicer looking title. titleize is meant for creating pretty output. It is not used in the Rails internals.

How do I camelize an acronym in a string?

An acronym must be specified as it will appear in a camelized string. An underscore string that contains the acronym will retain the acronym when passed to camelize, humanize, or titleize.

What does it mean to specify an acronym in a string?

Specifies a new acronym. An acronym must be specified as it will appear in a camelized string. An underscore string that contains the acronym will retain the acronym when passed to camelize, humanize, or titleize.

How do I capitalize the trailing ID in SQL Server?

The trailing ‘_id’,‘Id’.. can be kept and capitalized by setting the optional parameter keep_id_suffix to true. By default, this parameter is false. titleize is also aliased as titlecase.


1 Answers

You can do this by configuring ActiveSupport::Inflector, which provides the titleize method. Simply define your own inflections in an initializer.

# config/initializers/inflections.rb
ActiveSupport::Inflector.inflections do |inflect|
  inflect.acronym 'RV'
end

Restart your app to pick up the change. Now titleize knows how to handle "RV". Fire up a Rails console to check it out:

> "RvPark".titleize
=> "RV Park"
> "rv".titleize
=> "RV"

See the linked docs for more cool stuff you can do with inflections.

like image 64
Anson Avatar answered Oct 03 '22 07:10

Anson