Intelligent plural always intelligent? - ruby-on-rails

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?

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.

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

Related

How do you disable puralization of generated models in rails?

There's a config file config/initializers/inflections.rb that, as per this question lets you modify the puralization of certain items:
ruby on rails pluralization help?
However, I'm not interested in that. I want to turn the automatic modification of generated model names off.
Here's an example:
rails generate scaffold UserData data1:string data2:string
Data is changed to 'Datum':
%] cat app/models/user_datum.rb
class UserDatum < ActiveRecord::Base
attr_accessible :data1, :data2
end
This is undesirable behaviour.
How do I turn it off?
Specifically if you can please; I've seen a few threads with people saying things like 'you'll have to modify the recipe for that', but no actual guide to doing this.
(I appreciate people are going to want to start answering this with 'you should just stick to the rails way of doing things, there's a good reason for this and it'll work out in the long run'; please dont)
First of all, UserDatum is singular.
In any case:
Change your config/initializers/inflections.rb:
ActiveSupport::Inflector.inflections do |inflect|
inflect.uncountable %w(UserData)
end
(Use whatever naming convention you use, e.g., if you use underscores, user_data instead, or both.)
If you want to remove all pluralizations (sketchy: this will affect everything in the world):
ActiveSupport::Inflector.inflections do |inflect|
inflect.clear
inflect.singular(/$/i, '')
end
If you want to control only model/model file naming, patch ModelGenerator:
module Rails
module Generators
class ModelGenerator
def plural_name; singular_name; end
def plural_file_name; file_name; end
end
end
end
The best way of doing this is:
rails generate scaffold HouseData --force-plural
(it's still an item by item fix, but it doesn't mess around with the pluralization stuff, which is global and affects other parts of the app too)

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
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.
UPDATE: Acronym support was added to the Rails Inflector after I posted this.
See #Anson's answer for Rails 3.2 and up.
This looks like an edge-case that titleize wasn't designed for. The problem is the capitalize call inside will always turn RV into Rv.
I would create a generic name function for the models that call self.class.titleize internally, and then overload it in the RVPark model.

Ruby on Rails: How do you explicitly define plural names and singular names in Rails?

For example, I'm using "Bonus" as my model, so I'd expect "bonuses" to be the plural form and "bonus" to be the singular form.
However, in Ruby, this results in:
"bonus".pluralize # bonus
"bonuses".singularize # bonuse
So, when I do a "has_many :bonuses", for example, it doesn't use the Bonus.rb model (since Ruby expects a Bonuse.rb model instead). Is there a way to correct that in Ruby on Rails somehow such that "bonuses" acts as the plural form for the model bonus.rb?
In config/initializers, you will find a file called inflections.rb. There are some instructions in here, but you will want something along the lines of:
ActiveSupport::Inflector.inflections do |inflect|
inflect.irregular 'bonus', 'bonuses'
end
Just to back up bcarlso, more on Inflector can be found here:
http://4loc.wordpress.com/2009/04/09/inflector-rails-pluralization/
Note that the position of the Inflector.inflections block is important and, as noted in the link reference, must be after the Initializer.run block.
I believe you use the Inflector in your environment.rb (memory's a bit sketchy though)
If I remember correctly you put it in a block
Inflector.inflections { | i | i.irregular 'bonus', 'bonuses' }

Ruby On Rails: pluralize for other languages

I am building apps for a non-english audience. Right now, I use english nouns to name my models, yet I prefer to use native dutch ones. As the convention uses the plural of the class name for tables, I assume it is the pluralize method inside Rails (where it resides, I wouldn't know). How can I change the pluralize method and where is it located? Would this break Rails?
I am using Rails 2.3.5 and Ruby 1.8.7
Example:
The Book class becomes books now.
My Boek class becomes boeks, but it is grammatically correct to use boeken
Add your rules to an inflections.rb file in config/initializers. See the API documentation:
ActiveSupport::Inflector.inflections do |inflect|
inflect.plural 'boek', 'boeken'
end
Perhaps won't help you because you want Dutch language, but for Spanish, French, Kazakh, Turkish or Norwegian, there is this:
https://github.com/davidcelis/inflections
This is not answering the question specifically, but if a language has too much irregularities one can disable the inflector according to the discussion.
ActiveRecord::Base.pluralize_table_names = false
In addition, as far as views are concerned my preferred way of dealing with pluralizing foreign strings is i18n pluralization. Take a look at a straightforward example below.
# config/locales/en.yml
en:
message:
one: You have 1 message #Your foreign string
other: You have %{count} messages #Your foreign string
Then in view you can do
# app/views/messages/index.html.erb
<%= t("message", count: current_user.messages.count) %>
Check official documentation.
Hope that helps!

How do I get autotest to properly inflect singular models and plural controllers

Just as an example, if I have a Book model and a BooksController, autotest, part of the ZenTest suite will pick up the association between the two and load test/unit/book_test.rb and test/functional/books_controller_test.rb into the test suite. On the other hand, if I have a Story model and a StoriesController, autotest refuse to "notice" the test/functional/stories_controller_test.rb
Unfortunately ZenTest isn't a rails plugin, so it doesn't benefit from ActiveSupport's pluralize method. Therefore it uses simple regular expressions to match the filenames. Have a look at ZenTest/autotest/rails.rb to see a list of the existing mappings for Rails.
At the end you have two options:
(monkey) patch your own mapping rule
forget about pluralization
Hope this helps!
You can override the mappings in your .autotest file. Either in your home directory or at the root of the project. You could require 'active_support' there to get String#pluralize and String#singularize.
Borrow the code from the rspec-rails plugin in lib/autotest/rails_rspec.rb, it already seems to do the singular/plural magic with ActiveSupport. You'll probably need to yank out the RSpec specific assumptions from there, though.
I finally figured out what was going on, and it had nothing to do with pluralization after all.
It had everything to do with the word "stories" which can be a special directory for one of the testing libraries (RSpec? Cucumber? I forget) So it was listed in my ~/.autotest config file as an exception! I'm not sure when I cut and pasted the snippet into the file, probably when I was first getting starting with ZenTest and didn't know what I was really doing.
Autotest.add_hook :initialize do |at|
%w{... stories ...}.each {|exception|at.add_exception(exception)}
end
Adding a trailing slash ("stories/") restored the test and removed the brick marks from my forehead.
So I guess the lesson learned is: check for stray configuration files when debugging.

Resources