Ruby on rails DRY 从选择性输入表单中去除空白

Ruby on rails DRY strip whitespace from selective input forms

我是 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

编辑 II -- 成功

我将这个 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)

然后将其添加到任何模型中 class 这需要去除空格 ...

  include StripWhitespace
  strip_whitespace_from_attributes #add any attributes that need whitespace stripped

如果您可以将您的属性放入一个数组中(也许可以使用 [:params] 键),您可以执行以下操作:

class FooController < ApplicationController
  before_create strip_whitespace(params)



  private

  def strip_whitespace(*params)
    params.map{ |attr| attr.strip }
  end
end

我会这样去做(未测试):

module Stripper # yeah!
  extend ActiveSupport::Concern

  module ClassMethods
    def strip_attributes(*args)
      mod = Module.new
        args.each do |attribute|
          define_method "#{attribute}=" do |value|
            value = value.strip if value.respond_to? :strip
            super(value)
          end
        end
      end
      include mod
    end
  end
end

class MyModel < ActiveRecord::Base
  include Stripper
  strip_attributes :foo, :bar
end

m = MyModel.new
m.foo = '   stripped    '
m.foo #=> 'stripped'