Using titleize for abbreviation in Rails

I define some active entries with acronyms. RvPark (park of recreational parks). When I call the name of the class, I get "Rv Park". It really has to be "RV Park." Is there a good way to do this? Since this model shares the code with other models, I need to create a general solution, but I could not come up with it.

I saw a discussion about this, but there was no solution that would work for me. any understanding is appreciated.

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

+9
string ruby-on-rails
source share
2 answers

UPDATE: Aggressive support was added to Rails Inflector after I posted this.

See @Anson Answer for Rails 3.2 and above.


This is similar to an edge enclosure whose titleize is not intended title. The problem is a capitalize call inside will always turn an RV into an Rv.

I would create a generic name function for models that call self.class.titleize internally and then overload it in the RVPark model.

+3
source share

You can do this by setting up ActiveSupport :: Inflector , which provides titleize . Just define your own inflections in the initializer.

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

Restart the application to get the changes. Now titleize knows how to handle "RV". Launch the Rails console to verify:

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

See related documents for more interesting things you can do with kinks.

+16
source share

All Articles