在属性本身上查看模型属性帮助器

时间:2013-09-07 15:24:56

标签: ruby ruby-on-rails-3.2

我有:意思和:在我的视图模型上读取属性。我想运行sanitize before_validation来清理用户输入,然后再将其保存到DB。现在,而不是键入这样的东西:

before_validation :sanitize_input

def sanitize_input
  self.meaning = ActionController::Base.helpers.sanitize(self.meaning)
  self.reading = ActionController::Base.helpers.sanitize(self.reading)
end

我想让它更好一些。所以我想出了一个ActiveRecordExtension:

module ActiveRecordExtension
  extend ActiveSupport::Concern

  def sanitize_attribute(attribute)
    ActionController::Base.helpers.sanitize(attribute)
  end
end

ActiveRecord::Base.send(:include, ActiveRecordExtension)

现在我可以像这样调用输入清理:

def sanitize_input
  self.meaning = sanitize_attribute(self.meaning)
  self.reading = sanitize_attribute(self.reading)
end

我想通过在我的视图模型中做类似的事情(有点像属性本身的辅助方法)来缩短这一点:

def sanitize_input
  self.meaning.sanitize_attribute!
  self.reading.sanitize_attribute!
end

def sanitize_input
  sanitize_attribute!(self.meaning)
  sanitize_attribute!(self.reading)
end

但无论我尝试过什么,我都无法做到这一点(在我的sanitize_attribute方法中使用replace和bang(!)的各种组合。

使用类似的东西可以进一步缩短:

def sanitize_attributes!(*args)
  args.each do |arg|
    arg.replace ActionController::Base.helpers.sanitize(arg)
  end
end

并用以下内容调用它:

sanitize_attributes!(self.meaning, self.reading)

对于需要清理多个属性的情况,最后一个会很方便。它可以以某种方式完成我希望它完成的方式吗?

1 个答案:

答案 0 :(得分:1)

这些输入来自哪里,您必须手动清理它们?

试试这个:

def sanitize_attributes!(*attrs)
  attrs.each do |attr|
    dirty = self.send attr
    #this should mark the attribute as changed, so it's included with partial updates
    self.send "#{attr}=".to_sym, ActionController::Base.helpers.sanitize(dirty)
    #or
    #self.write_attribute(attr, ActionController::Base.helpers.sanitize(dirty))
  end
end

sanitize_attributes!(:meaning, :reading)