Sha256: 1a56d2151b1ce87b720b6c0c68574acbea31ef8933171e399938c0580e20d53e

Contents?: true

Size: 1.82 KB

Versions: 3

Compression:

Stored size: 1.82 KB

Contents

# * George Moschovitis  <gm@navel.gr>
# (c) 2004-2005 Navel, all rights reserved.
# $Id: validation.rb 301 2005-03-16 13:24:25Z gmosx $

require 'glue/validation'

module N 

# Extend the Validation methods defined in glue/validation.rb with 
# extra db related options.

module Validation

	# Encapsulates a list of validation errors.
	
	class Errors
		cattr_accessor :not_unique, 'The value is already used'
		cattr_accessor :invalid_relation, 'Invalid relations'
	end

	module MetaLanguage 

		# Validate the value of this attribute is unique
		# for this class.
		#
		# The Og libraries are required for this methdod to 
		# work. You can override this method if you want to
		# use another OR mapping library.
		#
		#--
		# TODO: :unique should implicitly generate 
		# validate_unique.
		#++

		def validate_unique(*params)
			c = { 
				:msg => N::Validation::Errors.not_unique, 
				:on => :save 
			}
			c.update(params.pop) if params.last.is_a?(Hash)

			for name in params
				# FIXME: improve the generated code.
				code = %{
					others = obj.class.find_by_#{name}(obj.#{name})
					unless (others.is_a?(Array) and others.empty?)
						errors.add(:#{name}, '#{c[:msg]}')
					end;
				}

				__meta[:validations] << [code, c[:on]]
			end
		end

		# Validate the related object or objects. Works
		# with all relations.
		
		def validate_related(*params)
			c = { 
				:msg => N::Validation::Errors.invalid_relation, 
				:on => :save 
			}
			c.update(params.pop) if params.last.is_a?(Hash)
			
			for name in params
				code = %{
					unless (obj.#{name}.is_a?(Array) ? obj.#{name} : [obj.#{name}]).inject(true) { |memo, obj| (obj.nil? or obj.valid?) and memo }
						errors.add(:#{name}, '#{c[:msg]}')
					end;
				}

				__meta[:validations] << [code, c[:on]]
			end
		end
		alias_method :validate_associated, :validate_related

	end
	
end 

end

Version data entries

3 entries across 3 versions & 1 rubygems

Version Path
og-0.13.0 lib/og/validation.rb
og-0.14.0 lib/og/validation.rb
og-0.15.0 lib/og/validation.rb