2

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.

TylerH
  • 20,799
  • 66
  • 75
  • 101
Mauricio Moraes
  • 7,255
  • 5
  • 39
  • 59

2 Answers2

2

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
miler350
  • 1,411
  • 11
  • 15
  • I already have some irregular inflections on my app, but for this case in particular I need a general rule. The example is just one of the cases of the something_of_something rule. I also translated my problem to make it better for SO, because the original is similar but is in portuguese. – Mauricio Moraes Jan 09 '15 at 18:46
  • Anyway, if there isn't a better generalized way, I'll use your idea! thanks – Mauricio Moraes Jan 09 '15 at 18:47
  • I just created a quick method that you can use. I didn't edit pluralize directly, but you can call this the same way as pluralize in your code. This would go in application helper. – miler350 Jan 09 '15 at 23:44
  • I think your method irregular_pluralize could be just string.gsub(/(^\w+)\s/, "\\1s "). I think this substitution with backreference may be the answer. This just needs to be put in a pluralization rule somehow. I can't try it out on my code right now, but I'll do try later. – Mauricio Moraes Jan 10 '15 at 14:19
1

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

Mauricio Moraes
  • 7,255
  • 5
  • 39
  • 59