Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Intelligent plural always intelligent?

Ruby on rails uses singular and plural conventions for model, view and controller names. This is very good, since one might have a model called user and a controller called users. This work with almost every word, such as user(s), tree(s), book(s), so every word that just has an s to form the plural.

However, what about words that do not just need an s to form the plural, such as words ending with the letter "y"? E.g., city and cities? Does rails know the difference or would I need to write city and citys, even though it is grammatically wrong?

like image 335
weltschmerz Avatar asked Sep 13 '12 19:09

weltschmerz


2 Answers

Rails knows a lot of plurals. It can handle "city," for example:

1.9.2p318 :001 > "city".pluralize
 => "cities" 
1.9.2p318 :002 > "cities".singular
 => "city"

However, you may find plurals it doesn't know, and won't be learning. See the documentation for ActiveSupport::Inflector

The Rails core team has stated patches for the inflections library will not be accepted in order to avoid breaking legacy applications which may be relying on errant inflections. If you discover an incorrect inflection and require it for your application, you’ll need to correct it yourself (explained below).

How do you correct it yourself? In config/initializers/inflections.rb. For example:

ActiveSupport::Inflector.inflections do |inflect|
  inflect.plural /^(.*)(l)ens$/i, '\1\2enses'
end

See again the docs for ActiveSupport::Inflector for more on how to teach rails new inflections.

like image 104
gregates Avatar answered Sep 25 '22 02:09

gregates


For a lot of common ones, it knows how to handle it pretty well. You can try this yourself in IRB by doing the following:

require 'active_support/all'
ActiveSupport::Inflector.pluralize("city")

And you'll get back a string with the value "cities". You can also add and adjust inflections by following the steps listed in config/initializers/inflections.rb

like image 34
agmcleod Avatar answered Sep 22 '22 02:09

agmcleod