Module: WingedCouch::Models::Validation::ClassMethods

Defined in:
lib/winged_couch/models/validation.rb

Constant Summary collapse

DEFAULT_ERROR_MESSAGE =
->(attribute_name) { "#{attribute_name} is required" }

Instance Method Summary collapse

Instance Method Details

#must_exist(attribute_name, options = {}) ⇒ Object

Defines presence validation and uploads it to CouchDB

Examples:

class User < WingedCouch::Model
  attribute :first_name, String
  must_exist :first_name
end

user = User.create(first_name: '')
# => #<User _id=nil>
user.errors
# => { name: ['is required'] }

Options Hash (options):

  • :message (String)

    error message


80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
# File 'lib/winged_couch/models/validation.rb', line 80

def must_exist(attribute_name, options = {})
  message = options[:message] || DEFAULT_ERROR_MESSAGE.call(attribute_name)
  text = %Q{
    function(newDoc) {
      if (newDoc._deleted) {
        return true;
      }
      var value = newDoc.#{attribute_name};
      if (value == null || value === "") {
        throw({forbidden: "#{message}"})
      }
    }
  }.strip

  current_validation = proc { Design::Validation.upload(database, attribute_name, text) rescue nil }
  validations << current_validation
  current_validation.call
end

#upload_validation!Object

Uploads all registered validations to CouchDB Alternatively, you can simple restart your app, It will trigger validations to be uploaded one by one

Examples:

class User < WingedCouch::Model
  attribute :first_name, String
  must_exist :first_name
end
User.upload_validations!
# Uploading ....

113
114
115
# File 'lib/winged_couch/models/validation.rb', line 113

def upload_validation!
  validations.each(&:call)
end