diff options
author | Mark Longair <mhl@pobox.com> | 2013-12-03 10:56:37 +0000 |
---|---|---|
committer | Mark Longair <mhl@pobox.com> | 2013-12-03 10:56:37 +0000 |
commit | 9e6810d0b86097e616192cf98554fc8ec664392a (patch) | |
tree | ae1c07545539e2ac35952636b72327d9bb3b7f0b /lib/strip_attributes/strip_attributes.rb | |
parent | b6f2d93f8daaffdc80cf656d7bfe4fbf933fb9eb (diff) | |
parent | 2720064fc7978b922e373a5fc69029eaff8efc6d (diff) |
Merge branch 'move-plugins-out-of-vendor-plugins' into rails-3-develop
Diffstat (limited to 'lib/strip_attributes/strip_attributes.rb')
-rw-r--r-- | lib/strip_attributes/strip_attributes.rb | 37 |
1 files changed, 37 insertions, 0 deletions
diff --git a/lib/strip_attributes/strip_attributes.rb b/lib/strip_attributes/strip_attributes.rb new file mode 100644 index 000000000..130d10185 --- /dev/null +++ b/lib/strip_attributes/strip_attributes.rb @@ -0,0 +1,37 @@ +module StripAttributes + # Strips whitespace from model fields and leaves nil values as nil. + # XXX this differs from official StripAttributes, as it doesn't make blank cells null. + def strip_attributes!(options = nil) + before_validation do |record| + attribute_names = StripAttributes.narrow(record.attribute_names, options) + + attribute_names.each do |attribute_name| + value = record[attribute_name] + if value.respond_to?(:strip) + stripped = value.strip + if stripped != value + record[attribute_name] = (value.nil?) ? nil : stripped + end + end + end + end + end + + # Necessary because Rails has removed the narrowing of attributes using :only + # and :except on Base#attributes + def self.narrow(attribute_names, options) + if options.nil? + attribute_names + else + if except = options[:except] + except = Array(except).collect { |attribute| attribute.to_s } + attribute_names - except + elsif only = options[:only] + only = Array(only).collect { |attribute| attribute.to_s } + attribute_names & only + else + raise ArgumentError, "Options does not specify :except or :only (#{options.keys.inspect})" + end + end + end +end |