【发布时间】:2015-07-08 14:24:08
【问题描述】:
我对 Rails 还很陌生,所以请耐心等待。
我想从一组选择性的输入表单中去除空格。
但我想要一个 DRY 解决方案。
所以我在想可能有一个解决方案,例如辅助方法或自定义回调。或者before_validation strip_whitespace(:attribute, :attribute2, etc)等组合
任何帮助都很棒!谢谢!
编辑
我的模型文件中有这个...
include ApplicationHelper
strip_whitespace_from_attributes :employer_name
...我的 ApplicationHelper 中有这个...
def strip_whitespace_from_attributes(*args)
args.each do |attribute|
attribute.gsub('\s*', '')
end
end
但现在我收到错误消息:
undefined method `strip_whitespace_from_attributes' for "the test":String
编辑二——成功
我将这个 StripWhitespace 模块文件添加到 lib 目录
module StripWhitespace
extend ActiveSupport::Concern
module ClassMethods
def strip_whitespace_from_attributes(*args)
args.each do |attribute|
define_method "#{attribute}=" do |value|
#debugger
value = value.gsub(/\s*/, "")
#debugger
super(value)
end
end
end
end
end
ActiveRecord::Base.send(:include, StripWhitespace)
然后将其添加到任何想要去除空格的模型类中......
include StripWhitespace
strip_whitespace_from_attributes #add any attributes that need whitespace stripped
【问题讨论】:
标签: ruby-on-rails ruby-on-rails-3 whitespace dry strip