Module | Scrivener::Validations |
In: |
lib/scrivener/validations.rb
|
Provides a base implementation for extensible validation routines. {Scrivener::Validations} currently only provides the following assertions:
The core tenets that Scrivener::Validations advocates can be summed up in a few bullet points:
Other validations are simply added on a per-model or per-project basis.
@example
class Quote attr_accessor :title attr_accessor :price attr_accessor :date def validate assert_present :title assert_numeric :price assert_format :date, /\A[\d]{4}-[\d]{1,2}-[\d]{1,2}\z end end s = Quote.new s.valid? # => false s.errors # => { :title => [:not_present], :price => [:not_numeric], :date => [:format] }
URL | = | /\A(http|https):\/\/([a-z0-9]+([\-\.]{1}[a-z0-9]+)*\.[a-z]{2,12}|(2 5[0-5]|2[0-4]\d|[0-1]?\d?\d)(\.(25[0-5]|2[0-4]\d|[0-1]?\d?\d)){3} |localhost)(:[0-9]{1,5})?(\/.*)?\z/ix |
= | /\A([\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+\.)* [\w\!\#$\%\&\'\*\+\-\/\=\?\^\`{\|\}\~]+@ ((((([a-z0-9]{1}[a-z0-9\-]{0,62}[a-z0-9]{1})|[a-z])\.)+ [a-z]{2,12})|(\d{1,3}\.){3}\d{1,3}(\:\d{1,5})?)\z/ix | |
DECIMAL | = | /\A\-?(\d+)?(\.\d+)?\z/ |
The grand daddy of all assertions. If you want to build custom assertions, or even quick and dirty ones, you can simply use this method.
@example
class CreatePost attr_accessor :slug attr_accessor :votes def validate assert_slug :slug assert votes.to_i > 0, [:votes, :not_valid] end protected def assert_slug(att, error = [att, :not_slug]) assert send(att).to_s =~ /\A[a-z\-0-9]+\z/, error end end
Check that the attribute has the expected value. It uses === for comparison, so type checks are possible too. Note that in order to make the case equality work, the check inverts the order of the arguments: `assert_equal :foo, Bar` is translated to the expression `Bar === send(:foo)`.
@example
def validate assert_equal :status, "pending" assert_equal :quantity, Fixnum end
@param [Symbol] att The attribute you wish to verify for equality. @param [Object] value The value you want to test against. @param [Array<Symbol, Symbol>] error The error that should be returned
when the validation fails.
Allows you to do a validation check against a regular expression. It‘s important to note that this internally calls {assert_present}, therefore you need not structure your regular expression to check for a non-empty value.
@param [Symbol] att The attribute you want to verify the format of. @param [Regexp] format The regular expression with which to compare
the value of att with.
@param [Array<Symbol, Symbol>] error The error that should be returned
when the validation fails.
Checks if all the characters of an attribute is a digit.
@param [Symbol] att The attribute you wish to verify the numeric format. @param [Array<Symbol, Symbol>] error The error that should be returned
when the validation fails.