Ruby on rails DRY从选择性输入表单中剥离空白

时间:2015-07-08 14:24:09

标签: ruby-on-rails ruby-on-rails-3 whitespace dry strip

我对铁轨很新,所以请耐心等待。

我想从一组选择性输入表单中删除空格。

但我想要一个干燥的解决方案。

所以我认为可能有一个解决方案,如帮助方法或自定义回调。或者是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)

然后将其添加到任何想要去除空格的模型类中......

  include StripWhitespace
  strip_whitespace_from_attributes #add any attributes that need whitespace stripped

2 个答案:

答案 0 :(得分:3)

我会像这样(未经测试)......

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'     

答案 1 :(得分:1)

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

class FooController < ApplicationController
  before_create strip_whitespace(params)



  private

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