el_quick
el_quick

Reputation: 4756

pluralize and singularize for spanish language

sorry for my english...

I have a rails application developed to spain, therefore, all content is in spanish, so, I have a search box to search in a mysql database, all rows are in spanish, I'd like to improve my search to allow to users to search keywords in singular or plural form, for example:

keyword: patatas
found: patata

keyword: veces
found: vez

keyword: vez
found: veces

keyword: actividades
found: actividad

In english, this could be relatively easy with help of singularize and pluralize methods ...

where `searching_field` like '%singularized_keyword%' or `searching_field` like '%pluralized_keyword%'

But, for spanish....

Some help?

Thanks!

Upvotes: 4

Views: 5079

Answers (4)

eloyesp
eloyesp

Reputation: 3285

It seems that it is now possible to use localized inflections now:

# config/initializers/inflections.rb
ActiveSupport::Inflector.inflections(:es) do |inflect|
  inflect.plural /([^djlnrs])([A-Z]|_|$)/, '\1s\2'
  inflect.plural /([djlnrs])([A-Z]|_|$)/, '\1es\2'
  inflect.plural /(.*)z([A-Z]|_|$)$/i, '\1ces\2'

  inflect.singular /([^djlnrs])s([A-Z]|_|$)/, '\1\2'
  inflect.singular /([djlnrs])es([A-Z]|_|$)/, '\1\2'
  inflect.singular /(.*)ces([A-Z]|_|$)$/i, '\1z\2'
end

With that (and after restarting the server) you can use:

"trebol".pluralize(:es) #=> "treboles"

Upvotes: 4

el_quick
el_quick

Reputation: 4756

I found this great way: http://www.slideshare.net/crnixon/advanced-internationalization-with-rails

Regards.

Upvotes: 5

juanmah
juanmah

Reputation: 1189

You have to clear all default inflections in English and create new ones in Spanish.

Add in config/initializers/inflections.rb

ActiveSupport::Inflector.inflections do |inflect|
  inflect.clear :all

  inflect.plural /([^djlnrs])([A-Z]|_|$)/, '\1s\2'
  inflect.plural /([djlnrs])([A-Z]|_|$)/, '\1es\2'
  inflect.plural /(.*)z([A-Z]|_|$)$/i, '\1ces\2'

  inflect.singular /([^djlnrs])s([A-Z]|_|$)/, '\1\2'
  inflect.singular /([djlnrs])es([A-Z]|_|$)/, '\1\2'
  inflect.singular /(.*)ces([A-Z]|_|$)$/i, '\1z\2'
end

Upvotes: 5

ffoeg
ffoeg

Reputation: 2336

You can define your own inflections now.

look in config/initializers/inflections.rb

an example based on your question

ActiveSupport::Inflector.inflections do |inflect|
  inflect.irregular 'patata', 'patatas'
end

Thus

"patata".pluralize # => "patatas"
"patatas".singularize #=> "patata"

Of course you need to know the list of keywords in advance to use the irregular method in config/inflections.rb. Have a look at the commented out examples in that file. There are other methods that allow one to define rules using regular expressions and you could devise pattern matches to affect inflections for arbitrary keywords that match known patterns.

Upvotes: 9

Related Questions