Ruby on Rails从选择性输入形式中DRY剥离空格 [英] Ruby on rails DRY strip whitespace from selective input forms

查看:58
本文介绍了Ruby on Rails从选择性输入形式中DRY剥离空格的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我对Rails还是很陌生,所以请耐心等待。

I'm fairly new to rails so bear with me.

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

I want to strip whitespace from a selective group of input forms.

但是我想要一个DRY解决方案。

But I would like a DRY solution.

所以我在想可能会有解决方案,例如辅助方法或自定义回调。或诸如 before_validation strip_whitespace(:attribute,:attribute2等)

So I was thinking there might be a solution such as a helper method, or a custom callback. Or a combination such as before_validation strip_whitespace(:attribute, :attribute2, etc)

任何帮助都很棒!谢谢!

Any help is awesome! Thanks!

编辑

我在模型文件中有此文件...

I have this in my model file ...

  include ApplicationHelper

  strip_whitespace_from_attributes :employer_name

...并且我在ApplicationHelper中有此文件...

... and I have this in my ApplicationHelper ...

  def strip_whitespace_from_attributes(*args)
    args.each do |attribute|
      attribute.gsub('\s*', '')
    end
  end

但现在我收到错误消息:

but now I'm getting the error message:

undefined method `strip_whitespace_from_attributes' for "the test":String

编辑II-成功

我将此StripWhitespace模块文件添加到lib目录

I added this StripWhitespace module file to the lib directory

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)

,然后将其添加到要删除空格的任何模型类中……

and then added this to any model class this wants to strip whitespace ...

  include StripWhitespace
  strip_whitespace_from_attributes #add any attributes that need whitespace stripped


推荐答案

我会像这样(未测试):

I would go with sth like this (not tested):

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'     

这篇关于Ruby on Rails从选择性输入形式中DRY剥离空格的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆