1

We've got an app that deals with crops like tomatoes, beans, and squash.

  • One bean, many beans
  • One tomato, many tomatoes
  • One squash, many squash

Some of the crops have very weird plural forms, eg. you never pick "one garlic" you pick "one head of garlic". Some are almost never referred to in the singular, eg. "oats" -- you don't plant "one oat".

We use these words in sentences like, "Bob planted 3 tomatoes" or "Mary harvested 3 kg of oats".

So we want to use the Rails inflector to configure some special cases. However, we want to store the details of this in our database alongside other information about crops. Our users will be able to update the record to list the correct singular or plural forms.

We've read up on how to use the inflector but everything suggests configuring it in config/ somewhere, which means we'd have to restart the app for changes to take effect. How can we pick up new inflection information from the database as it changes?

We're using Rails 3.2 but would welcome Rails 4 answers if that's needed, as we're likely to be upgrading sometime soonish anyway.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Skud
  • 238
  • 2
  • 7

1 Answers1

0

You can use the 'inflections' singleton to define rules dynamically as you load crops from your database. Assuming you store singular form in an attribute singular and plural in attribute plural...

class Crop < ActiveRecord::Base
  after_find do |crop|
    ActiveSupport::Inflector.inflections.plural(crop.singular, crop.plural) if crop.singular
  end
  ...
end

And of course you just then use the pluralize method as usual...

ActiveSupport::Inflector.inflections.plural("beatle", "mopheads")

p "beatle".pluralize
=> "mopheads"
SteveTurczyn
  • 36,057
  • 6
  • 41
  • 53