Module: RailsExtension::ActiveRecordExtension::Base::ClassMethods

Defined in:
lib/rails_extension/active_record_extension/base.rb

Instance Method Summary collapse

Instance Method Details

#randomObject



8
9
10
11
12
13
14
15
# File 'lib/rails_extension/active_record_extension/base.rb', line 8

def random
	count = count()
	if count > 0
		first(:offset => rand(count))
	else
		nil
	end
end

#validates_absence_of(*attr_names) ⇒ Object



17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
# File 'lib/rails_extension/active_record_extension/base.rb', line 17

def validates_absence_of(*attr_names)
	configuration = { :on => :save,
		:message => "is present and must be absent." }
	configuration.update(attr_names.extract_options!)

	send(validation_method(configuration[:on]), configuration) do |record|
		attr_names.each do |attr_name|
			unless record.send(attr_name).blank?
				record.errors.add(attr_name, 
					ActiveRecord::Error.new(record,attr_name,:present,
						{ :message => configuration[:message] }))
			end
		end
	end
end

#validates_complete_date_for(*attr_names) ⇒ Object

This doesn’t work as one would expect if the column is a DateTime instead of just a Date. For some reason, *_before_type_cast actually returns a parsed DateTime?



54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
# File 'lib/rails_extension/active_record_extension/base.rb', line 54

def validates_complete_date_for(*attr_names)
	configuration = { :on => :save,
		:message => "is not a complete date." }
	configuration.update(attr_names.extract_options!)

	send(validation_method(configuration[:on]), configuration) do |record|
		attr_names.each do |attr_name|

			value = record.send("#{attr_name}_before_type_cast")
			unless( configuration[:allow_nil] && value.blank? ) ||
				( !value.is_a?(String) )
				date_hash = Date._parse(value)
				unless date_hash.has_key?(:year) &&
					date_hash.has_key?(:mon) &&
					date_hash.has_key?(:mday)
					record.errors.add(attr_name, 
						ActiveRecord::Error.new(record,attr_name,:not_complete_date,
							{ :message => configuration[:message] }))
				end
			end
		end
	end
end

#validates_past_date_for(*attr_names) ⇒ Object



33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
# File 'lib/rails_extension/active_record_extension/base.rb', line 33

def validates_past_date_for(*attr_names)
	configuration = { :on => :save,
		:message => "is in the future and must be in the past." }
	configuration.update(attr_names.extract_options!)

	send(validation_method(configuration[:on]), configuration) do |record|
		attr_names.each do |attr_name|
			date = record.send(attr_name)
			if !date.blank? && Time.now < date
				record.errors.add(attr_name, 
					ActiveRecord::Error.new(record,attr_name,:not_past_date,
						{ :message => configuration[:message] }))
			end
		end
	end
end