Skip to content

Instantly share code, notes, and snippets.

@julik
Created April 13, 2010 13:02
Show Gist options
  • Save julik/364576 to your computer and use it in GitHub Desktop.
Save julik/364576 to your computer and use it in GitHub Desktop.
class ActiveRecord::Base
before_validation :strip_whitespace_from_attributes!, :stringify_content_attributes!
private
# Will strip trailing and leading whitespace from all attributes and convert
# empty strings to nil.
def strip_whitespace_from_attributes!
for col in self.class.content_columns.collect{|c| c.name.to_sym}
if !self[col].nil? && self[col].respond_to?(:strip)
s = self[col].strip.gsub(/\r\n?/, "\n")
s.size == 0 ? self[col] = nil : self[col] = s
end
end
end
# Will convert symbols to strings
def stringify_content_attributes!
for col in self.class.content_columns.collect{|c| c.name.to_sym}
self[col] = self[col].to_s if self[col].is_a?(Symbol)
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment