Paul Philippov

home is where ~/ is

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?