Last active
April 12, 2017 01:25
-
-
Save patorash/731d07a4f26e9982b66dfa01aa56fe49 to your computer and use it in GitHub Desktop.
文字列型のカラムのデータを検証前にtrim(strip)する
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 文字列型のカラムのデータを検証前にstripする | |
concern :StringStripper do | |
included do | |
# self.columnsはテーブルのスキーマ情報からロードされるため、テーブルがまだないときは何もしない | |
proc = if ActiveRecord::VERSION::MAJOR > 4 | |
Proc.new { ActiveRecord::Base.connection.data_source_exists? self.table_name } | |
else | |
Proc.new { ActiveRecord::Base.connection.table_exists? self.table_name } | |
end | |
if proc.call | |
# 純粋な文字列型のカラムのみ抽出(文字列の配列型を除外) | |
string_columns = self.columns.find_all do |column| | |
%i(string text).include?(column.sql_type_metadata.type) && column.array? == false | |
end | |
unless string_columns.blank? | |
before_validation do |model| | |
string_columns.each do |column| | |
before_cast = model.__send__("#{column.name}_before_type_cast") | |
model.__send__("#{column.name}=", before_cast.strip) unless before_cast.blank? | |
end | |
end | |
end | |
end | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment