Rails 3在所有表单上删除before_validation的空格

时间:2010-11-28 01:56:18

标签: ruby-on-rails validation whitespace dry helpers

我对Rails相对较新,有点惊讶这不是一个可配置的行为......至少没有一个我能找到的?!?我原以为99%的表格会受益于所有string& text字段?!?猜猜我错了......

无论如何,我正在寻找一种干燥的方法来从Rails 3应用程序中的表单字段(类型:string&:text)中删除所有空格。

视图有自动引用(包含?)并可供每个视图使用的助手......但模型似乎没有这样的东西?!?或者他们呢?

所以目前我正在执行以下操作首先 需要然后 包含 whitespace_helper(又名WhitespaceHelper)。但这对我来说似乎仍然不是很干,但它有效...

ClassName.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/?),它会获取一个params(或属性)列表并删除空格({{1每个属性w / out都是专门命名的。

3 个答案:

答案 0 :(得分:7)

创建一个before_validation帮助器,如here

所示
module Trimmer
  def trimmed_fields *field_list  
    before_validation do |model|
      field_list.each do |n|
        model[n] = model[n].strip if model[n].respond_to?('strip')
      end
    end
  end
end

require 'trimmer'
class ClassName < ActiveRecord::Base
  extend Trimmer
  trimmed_fields :attributeA, :attributeB
end

答案 1 :(得分:1)

使用AutoStripAttributes gem for Rails。它将帮助您轻松,干净地完成任务。

class User < ActiveRecord::Base
 # Normal usage where " aaa   bbb\t " changes to "aaa bbb"
  auto_strip_attributes :nick, :comment

  # Squeezes spaces inside the string: "James   Bond  " => "James Bond"
  auto_strip_attributes :name, :squish => true

  # Won't set to null even if string is blank. "   " => ""
  auto_strip_attributes :email, :nullify => false
end

答案 2 :(得分:0)

注意我还没试过这个,这可能是一个疯狂的想法,但你可以创建一个这样的类:

MyActiveRecordBase < ActiveRecord::Base
  require 'whitespace_helper'  
  include WhitespaceHelper
end

...然后让你的模型继承而不是AR :: Base:

MyModel < MyActiveRecordBase
  # stuff
end