Module: ActiveRecord::Blanks

Defined in:
lib/active_record/blanks.rb,
lib/active_record/blanks/version.rb

Constant Summary collapse

VERSION =
"1.0.0"

Class Method Summary collapse

Instance Method Summary collapse

Class Method Details

.prepended(base) ⇒ Object


52
53
54
# File 'lib/active_record/blanks.rb', line 52

def self.prepended(base)
	base.before_validation :convert_blanks
end

Instance Method Details

#blank_columnsObject


25
26
27
28
29
30
31
32
33
# File 'lib/active_record/blanks.rb', line 25

def blank_columns
	return to_enum(:blank_columns) unless block_given?
	
	self.class.columns.each do |column|
		if column.null
			yield column
		end
	end
end

#convert_blanks(to = nil) ⇒ Object


35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
# File 'lib/active_record/blanks.rb', line 35

def convert_blanks(to = nil)
	blank_columns do |column|
		value = read_attribute(column.name)
		
		next unless value.is_a?(String)
		
		# Strip leading and trailing whitespace:
		value = value.strip
		
		if value.blank?
			write_attribute(column.name, to)
		else
			write_attribute(column.name, value)
		end
	end
end