我对 Rails 比较陌生,有点惊讶这不是一种可配置的行为……至少我还没有找到?!?我原以为 99% 的表单会受益于从所有string
&text
字段中修剪空白?!?估计我错了...
无论如何,我正在寻找一种 DRY 方法来从 Rails 3 应用程序中的表单字段(类型:string 和:text)中删除所有空格。
视图具有自动引用(包括?)并且可用于每个视图的助手......但是模型似乎没有这样的东西?!?还是他们?
因此,目前我执行以下操作,首先需要然后包含 whitespace_helper(又名WhitespaceHelper)。但这对我来说似乎仍然不是很干燥,但它有效......
类名.rb:
require 'whitespace_helper'
class ClassName < ActiveRecord::Base
include WhitespaceHelper
before_validation :strip_blanks
...
protected
def strip_blanks
self.attributeA.strip!
self.attributeB.strip!
...
end
lib/whitespace_helper.rb:
module WhitespaceHelper
def strip_whitespace
self.attributes.each_pair do |key, value|
self[key] = value.strip if value.respond_to?('strip')
end
end
我想我正在寻找一个单一的(DRY)方法(类?)放在某个地方(lib/
?),它将获取参数(或属性)列表并.strip!
从每个属性中删除空格(?)没有被特别命名.