| Module | StripAttributes |
| In: |
lib/strip_attributes.rb
|
Necessary because Rails has removed the narrowing of attributes using :only and :except on Base#attributes
# File lib/strip_attributes.rb, line 16
16: def self.narrow(attributes, options)
17: if options.nil?
18: attributes
19: else
20: if except = options[:except]
21: except = Array(except).collect { |attribute| attribute.to_s }
22: attributes.except(*except)
23: elsif only = options[:only]
24: only = Array(only).collect { |attribute| attribute.to_s }
25: attributes.slice(*only)
26: else
27: raise ArgumentError, "Options does not specify :except or :only (#{options.keys.inspect})"
28: end
29: end
30: end
Strips whitespace from model fields and converts blank values to nil.
# File lib/strip_attributes.rb, line 3
3: def strip_attributes!(options = nil)
4: before_validation do |record|
5: attributes = StripAttributes.narrow(record.attributes, options)
6: attributes.each do |attr, value|
7: if value.respond_to?(:strip)
8: record[attr] = (value.blank?) ? nil : value.strip
9: end
10: end
11: end
12: end