I have an ActiveRecord model, Foo, which has a name field. I’d like users to be able to search by name, but I’d like the search to ignore case and any accents. Thus, I’m also storing a canonical_name field against which to search:
class Foo validates_presence_of :name before_validate :set_canonical_name private def set_canonical_name self.canonical_name ||= canonicalize(self.name) if self.name end def canonicalize(x) x.downcase. # something here end end
I need to fill in the ‘something here’ to replace the accented characters. Is there anything better than
x.downcase.gsub(/[àáâãäå]/,'a').gsub(/æ/,'ae').gsub(/ç/, 'c').gsub(/[èéêë]/,'e')....
And, for that matter, since I’m not on Ruby 1.9, I can’t put those Unicode literals in my code. The actual regular expressions will look much uglier.
Rails has already a builtin for normalizing, you just have to use this to normalize your string to form KD and then remove the other chars (i.e. accent marks) like this: