Mauricio Moraes
Mauricio Moraes

Reputation: 7373

Pluralization rule for some compound terms in Rails

I want to create a pluralization rule for some terms that aren't correctly pluralized. I'll place it on my inflections.rb file.

The terms are some compound ones that I may pluralize the first word, instead of the second, but, in my case, I don't have the option to apply the pluralize function on the first term only. For example:

'base of knowledge'.pluralize should return 'bases of knowledge' instead of 'base of knowledges'

I tried a regexp like this one /\sof\s/ to find the of part on the string, but could't write a rule to inflect correctly.

inflect.plural(???, ???)

Obs: I'm not looking for a linguistic workaround, like 'knowledge base'. The example is merely illustrative.

Upvotes: 2

Views: 465

Answers (2)

Mauricio Moraes
Mauricio Moraes

Reputation: 7373

I've found a way to inflect the compound term by adding this rule:

inflect.plural(/(^\w+)\s(of\s\w+)/i, '\1s \2')

Then I got:

'base of knowledge'.pluralize -> 'bases of knowledge'

as expected

Upvotes: 1

miler350
miler350

Reputation: 1421

Try this:

  1. Create a file called: config/initializers/inflections.rb

  2. Simple non-dynamic example:

    ActiveSupport::Inflector.inflections do |inflect|
      inflect.irregular 'base of knowledge', 'bases of knowledge'
    end
    

    This just requires you to specify each irregular plural phrase instead of a word. As long you call the pluralize method, it will find it.

Edit:

If you just want one method to handle all these types of changes. You could define an irregular_pluralize method that accepts the same inputs as pluralize or that accepts 3 objects.

def irregular_pluralize(count, string)
  if count > 1
    split_string = string.split(" ")
    size = split_string.size
    first = split_string.first
    first.pluralize + " " + split_string.last(size - 1).join(" ")
  else
    string
  end
end

Upvotes: 2

Related Questions