【问题标题】:Ruby on rails DRY strip whitespace from selective input formsRuby on rails DRY 从选择性输入表单中去除空格
【发布时间】:2015-07-08 14:24:08
【问题描述】:

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

编辑二——成功

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

【问题讨论】:

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


    【解决方案1】:

    我会这样(未测试):

    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'     
    

    【讨论】:

    • @KendallWeihe - 我不确定在模型中包含 ApplicationHelper 何时如此受欢迎,或者为什么。助手是与视图相关联的模块,因此将它们包含在模型中会破坏 MVC 模式。除此之外,您尝试在类上下文中调用的方法被定义为实例方法,因此它不可用。
    • @BroiSatse 将该方法添加到控制器中怎么样?这会破坏 MVC 模式吗?
    【解决方案2】:

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

    class FooController < ApplicationController
      before_create strip_whitespace(params)
    
    
    
      private
    
      def strip_whitespace(*params)
        params.map{ |attr| attr.strip }
      end
    end
    

    【讨论】:

    • 我认为控制器上没有定义before_validation方法。
    猜你喜欢
    • 2010-11-04
    • 1970-01-01
    • 2014-12-25
    • 1970-01-01
    • 1970-01-01
    • 2012-11-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多