Class: BsonObjectIdValidations::LegalBsonObjectIdValidator

Inherits:
ActiveModel::EachValidator
  • Object
show all
Defined in:
lib/bson_object_id_validations/legal_bson_object_id_validator.rb

Constant Summary collapse

@@error_message =
'is not a legal BSON::ObjectId'

Instance Method Summary collapse

Instance Method Details

#validate_each(record, attribute, value) ⇒ Object

Validate that the specified attribute’s value is a legal BSON::ObjectId .

Examples:

class User
  include ActiveModel::Validations

  attr_accessor :mongo_id

  validates :mongo_id, :legal_bson_object_id => true
end

user = User.new :mongo_id => "invalid"

user.valid?
 => false

user.errors
 => {:mongo_id=>["is an invalid BSON::ObjectId"]}

user.mongo_id = BSON::ObjectId.new.to_s

user.valid?
 => true


29
30
31
32
33
34
35
# File 'lib/bson_object_id_validations/legal_bson_object_id_validator.rb', line 29

def validate_each(record, attribute, value)
  error_message = options[:message] || @@error_message

  unless ::BSON::ObjectId.legal? value
    record.errors.add attribute, error_message
  end
end