[Ruby] Normalize Rails values

less than 1 minute read

Value normalization

It is called canonical to transform information so that it follows certain rules. This time, if the value entered for reading was hiragana, normalize it. I will try to normalize it into katakana.

First, create a normalizer in the app/models/concerns directory.

string_normalizer.rb



require "nkf"

module StringNormalizer
  def normalize_as_furigana(text)
    NKF.nkf("-W -w -Z1 --katakana", text).strip if text
end

The following code actually does the normalization.

NKF.nkf("-W -w -Z1 --katakana", text).strip if text

The specified arguments have the following meanings.

Argument of NKF#nkf method

Flag Meaning  
- W Input character code is UTF-8  
-w Output in UTF-8  
- Z1 Full-width alphanumeric characters, symbols, half-width spaces are changed to half-width w
–katakana Convert Hiragana to Katakana  

Now you’re ready. After that, let’s install the module on the model side

model.rb


class UserController <ApplicationRecord
  include StringNormalizer

  before_validation do
    self.name_kana = normalize_as_furigana(name_kana)
  end

Before passing the validation like this, the attribute specified in name_kana I was able to normalize to Hiragana -> Katakana.

That’s all for today! !!

Tags: ,

Updated: