Paul Philippov

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. to How to upcase multibyte data in Rails

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

over 10 years ago

Paul Philippov to How to upcase multibyte data in Rails

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."

over 10 years ago

Josue to How to upcase multibyte data in Rails

Muchas gracias me ayudaste muchisimo.
Thanks

about 8 years ago