Handling acronyms in rails
The ActiveSupport::Inflector
handles a lot of the semantic rules in Rails, including acronyms.
The inflections method yields to a singleton instance of ActiveSupport::Inflector::Inflections
. It can be passed an optional locale, which is how we could write inflection rules for other languages; the default locale is English (specified as the argument :en
).
We can write our own inflections inside of the config/initializers/inflections.rb
file. This file actually already exists and will look like this when we first open it:
# Be sure to restart your server when you modify this file.
# Add new inflection rules using the following format. Inflections
# are locale specific, and you may define rules for as many different
# locales as you wish. All of these examples are active by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.plural /^(ox)$/i, '\1en'
# inflect.singular /^(ox)en/i, '\1'
# inflect.irregular 'person', 'people'
# inflect.uncountable %w( fish sheep )
# end
# These inflection rules are supported but not enabled by default:
# ActiveSupport::Inflector.inflections(:en) do |inflect|
# inflect.acronym 'RESTful'
# end
We can already see how to go about writing our inflections with the examples in this file.
ActiveSupport::Inflector.inflections(:en) do |inflect|
inflect.acronym 'RESTfull'
inflect.acronym 'NRI'
end
# acronym 'RESTful'
'RESTful'.underscore # => 'restful'
'RESTfulController'.underscore # => 'restful_controller'
'RESTfulController'.titleize # => 'RESTful Controller'
'restful'.camelize # => 'RESTful'
'restful_controller'.camelize # => 'RESTfulController'
# acronym 'NRI'
'NRI'.underscore # => 'nri'
'nri'.camelize # => 'NRI'
'nri'.titleize # => 'NRI'
'nri'.humanize # => 'NRI'
References:
- Rails ActiveSupport::Inflector::Inflection : http://api.rubyonrails.org/classes/ActiveSupport/Inflector/Inflections.html#method-i-acronym