How to upcase multibyte data in Rails

In one of my projects I needed that all data sent to a model were converted in upper case prior they validated and then saved, once valid. I’ve chosen to keep them in upper case for better readability. There was no problem with converting ASCII data. Everything worked like a charm. Problem started when I tried to save data in Cyrillic. upcase! just refused to modify non-ASCII characters.

Here’s how I made it to work, finally.

class Address < ActiveRecord::Base
  before_validation :uppercase_data

  def uppercase_data
    %w{street city state country}.each do |x|
      self.send("#{x}=", self.send(x).mb_chars.upcase.to_s)
    end
  end
end

Maybe someone will suggest a more elegant solution?

Comments (3)

Alexander S. over 4 years ago

Very nice solution.
Do you know if there is any reason why upcase won't work with utf-8, French accented characters?

Paul Philippov over 4 years ago

I believe the reason is Ruby. Both #upcase and #upcase! methods have the same note in descriptions: "case replacement is effective only in ASCII region."

Josue almost 2 years ago

Muchas gracias me ayudaste muchisimo.
Thanks