Posts Tagged ‘couchrest’

Simple validations in CouchRest::Model

Monday, November 17th, 2008

Since I’m having no joy on the CouchRest support forum or in mail to the author, here’s a monkeypatch to implement simple field validations in CouchRest::Model.

module CouchRest
 
  class Model
 
  class_inheritable_accessor :validation_fields
 
  def self.validate *fields
    self.validation_fields = fields.map {|f| f.to_s}
  end
 
  def valid?
    self.invalid_fields.blank?
  end
 
  def invalid_fields
    return [] unless self.validation_fields
    check = self.validation_fields.clone
    self.validation_fields.each do |c|
      check.delete_if {|x| x == c } if !self[c].blank?
    end
    return check
  end
 
  def save
    if new_record?
      create if self.valid?
    else
      update
    end
  end
 
  end # class Model
 
end # module CouchRest

Just throw a line like validate :field1, :field2, :field3 anywhere in the Model and it’ll refuse to save without those fields being present.

Stay tuned for the upcoming $9 screencast on use of this incredible new feature, development of which has taken minutes of my precious, precious time.