Module: N::Validation

Defined in:
lib/glue/validation.rb

Overview

Implements a meta-language for validating managed objects. Typically used in Validator objects but can be included in managed objects too.

Example

class User prop_accessor :name, String prop_accessor :level, Fixnum

validate_length :name, :range => 2..6 validate_unique :name, :msg => :name_allready_exists validate_format :name, :format => /[a-z]*/, :msg => ‘invalid format’, :on => :create end

class N::CustomUserValidator include N::Validation validate_length :name, :range => 2..6, :msg_short => :name_too_short, :msg_long => :name_too_long end

user = @request.fill(User.new) user.level = 15

unless user.valid? user.save else p user.errors end

unless user.save p user.errors.on(:name) end

unless errors = N::CustomUserValidator.errors(user) user.save else p errors end

– TODO: all validation methods should imply validate_value TODO: add validate_unique ++

Defined Under Namespace

Modules: MetaLanguage Classes: Errors

Instance Attribute Summary collapse

Class Method Summary collapse

Instance Method Summary collapse

Instance Attribute Details

#errorsObject

If the validate method returns true, this attributes holds the errors found.



104
105
106
# File 'lib/glue/validation.rb', line 104

def errors
  @errors
end

Class Method Details

.append_features(base) ⇒ Object



150
151
152
153
154
155
156
157
158
# File 'lib/glue/validation.rb', line 150

def self.append_features(base)
	super

	base.module_eval <<-"end_eval", __FILE__, __LINE__
		meta :validations, []
	end_eval

	base.extend(MetaLanguage)
end

.eval_validate(klass) ⇒ Object

Evaluate the ‘validate’ method for the calling class.

WARNING: for the moment only evaluates for on == :save



128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
# File 'lib/glue/validation.rb', line 128

def self.eval_validate(klass)
	code = %{	
		def self.validate(obj, on = :save)
			errors = Errors.new
	}

	for val, on in klass.__meta[:validations]
		code << %{
			#{val}
		} 
	end

	code << %{
			return errors
		end		
	}

	# puts '-->', code, '<--'

	klass.module_eval(code)
end

Instance Method Details

#valid?Boolean

Call the #validate method for this object. If validation errors are found, sets the returns true.

Returns:

  • (Boolean)


111
112
113
114
115
116
117
118
119
120
# File 'lib/glue/validation.rb', line 111

def valid?
	begin
		@errors = self.class.validate(self)
		return @errors.empty?
	rescue NoMethodError => e
		# gmosx: hmm this is potentially dangerous.
		N::Validation.eval_validate(self.class)
		retry 
	end
end