Skip to content

Instantly share code, notes, and snippets.

@alpaca-tc
Created May 23, 2021 13:42
Show Gist options
  • Save alpaca-tc/c105905c8f3c2b06c6c5428edf25fa72 to your computer and use it in GitHub Desktop.
Save alpaca-tc/c105905c8f3c2b06c6c5428edf25fa72 to your computer and use it in GitHub Desktop.
渡された値から数値以外を削除する型(主に電話番号用)
# Usage
# attribute :phone_number, :number_string
class NumberString < ActiveModel::Type::String
# 与えられた値を数値のみの文字列、またはnilに変換する
#
# @param value [Object]
#
# @return [String, NilClass]
def cast(value)
super(value)&.remove(/\D/)
end
# 与えられた値をDBのクエリ用に変換する
#
# @param value [Object]
#
# @return [String, NilClass]
def serialize(value)
cast(value)
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment