リア充爆発日記

You don't even know what ria-ju really is.

Railsでバリデーション前に文字列の前後のスペースやタブを取り除くメモ

ベースにこれを使う。
https://github.com/holli/auto_strip_attributes

gem "auto_strip_attributes", "~> 2.0"

で、これだけだと全角スペースには対応してないけど、さいわい好きな処理を挟めるフィルター機能があるのでそれを使う。っていうか、これ使うともう別にstripじゃなくてもなんでもよくなるっていうか。

config/initializers/auto_strip_attributes.rb

AutoStripAttributes::Config.setup do
  set_filter strip_zenkaku: false do |value|
    value.gsub(/(^(\s| )+)|((\s| )+$)/, '') unless value.nil? or !value.kind_of?(String)
  end
end

model

~snip~
auto_strip_attributes :title, :description, strip_zenkaku: true
~snip~

spec

~snip~
    context 'strip' do
      before { @article.title = "\t  " + ("" * MyModel::MAX_LENGTH_TITLE) + "\t  "}
      it { should be_valid }
    end
~snip~