Normalize Rails values

Value normalization

Converting information to follow certain rules is called legitimate. This time, if the value entered as Frigana is Hiragana, normalize it. Let's try normalization to make it katakana.

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


require "nkf"

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

The code below does the actual normalization.

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

The arguments specified have the following meanings:

** NKF # nkf method arguments **

flag meaning
-W Input character code is UTF-8
-w UTF-Output at 8
-Z1 Change full-width alphanumeric characters, symbols, and half-width spaces to half-width
--katakana Convert hiragana to katakana

You are now ready. After that, let's install the module on the model side


class UserController < ApplicationRecord
  include StringNormalizer

  before_validation do
    self.name_kana = normalize_as_furigana(name_kana)

Attribute specified by name_kana before passing validation like this I was able to normalize to Hiragana-> Katakana.

That's all for today! !!

Recommended Posts

Normalize Rails values
[Rails g.error]
Rails basics
Rails Review 1
Rails API
Rails migration
[Rails] first_or_initialize
rails tutorial
About Rails 6
Rails foundation
Rails memorandum
rails tutorial
rails tutorial
rails tutorial
[Rails] devise
rails tutorial
rails tutorial
Rails Tips
rails method
rails tutorial
Rails Review 2