Sha256: 9a0d65ee7c47d02ab9df7bcc6a0adac075fe47bd0f35a2d5bc674683406282da

Contents?: true

Size: 1.7 KB

Versions: 5

Compression:

Stored size: 1.7 KB

Contents

require 'glue/validation'

module Glue 

# 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 => Glue::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 => Glue::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

5 entries across 5 versions & 1 rubygems

Version Path
og-0.17.0 lib/og/validation.rb
og-0.18.1 lib/og/validation.rb
og-0.20.0 lib/og/validation.rb
og-0.18.0 lib/og/validation.rb
og-0.19.0 lib/og/validation.rb