Skip to content

Instantly share code, notes, and snippets.

@patorash
Last active April 12, 2017 01:25
Show Gist options
  • Save patorash/731d07a4f26e9982b66dfa01aa56fe49 to your computer and use it in GitHub Desktop.
Save patorash/731d07a4f26e9982b66dfa01aa56fe49 to your computer and use it in GitHub Desktop.
文字列型のカラムのデータを検証前にtrim(strip)する
# 文字列型のカラムのデータを検証前に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