ビューモデルに :meaning 属性と :reading 属性があります。DB に保存する前に、サニタイズ before_validation を実行してユーザー入力をクリーンアップしたいと考えています。さて、次のように入力する代わりに:
before_validation :sanitize_input
def sanitize_input
self.meaning = ActionController::Base.helpers.sanitize(self.meaning)
self.reading = ActionController::Base.helpers.sanitize(self.reading)
end
もう少し綺麗にしたかった。そこで、ActiveRecordExtension を思いつきました。
module ActiveRecordExtension
extend ActiveSupport::Concern
def sanitize_attribute(attribute)
ActionController::Base.helpers.sanitize(attribute)
end
end
ActiveRecord::Base.send(:include, ActiveRecordExtension)
これで、次のように入力のサニタイズを呼び出すことができます。
def sanitize_input
self.meaning = sanitize_attribute(self.meaning)
self.reading = sanitize_attribute(self.reading)
end
ビューモデルで次のようなこと(属性自体のヘルパーメソッドのようなもの)を行うことで、これを少し短縮したいと思います。
def sanitize_input
self.meaning.sanitize_attribute!
self.reading.sanitize_attribute!
end
また
def sanitize_input
sanitize_attribute!(self.meaning)
sanitize_attribute!(self.reading)
end
しかし、何を試しても、これを機能させることができませんでした (sanitize_attribute メソッドで replace と bang (!) を使用するさまざまな組み合わせ。
次のようなものを使用して、さらに短縮できますか。
def sanitize_attributes!(*args)
args.each do |arg|
arg.replace ActionController::Base.helpers.sanitize(arg)
end
end
そしてそれを次のようなもので呼び出します:
sanitize_attributes!(self.meaning, self.reading)
最後の属性は、サニタイズが必要な属性が複数ある場合に便利です。私がやりたい方法の1つで、どうにかしてそれを行うことはできますか?