Created
August 24, 2011 16:49
-
-
Save murdoch/1168510 to your computer and use it in GitHub Desktop.
strip white-space from all attributes
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Just a few different methods to strip white-space from all attributes on a model. | |
# method 1 - code from scott moonen | |
# http://scottmoonen.com/2009/05/08/rails-pattern-trim-spaces-on-input/ | |
module Trimmer | |
def self.included base | |
base.extend(ClassMethods) | |
end | |
module ClassMethods | |
def trimmed_fields *field_list | |
before_validation do |model| | |
field_list.each do |n| | |
model[n] = model[n].strip if model[n].respond_to?('strip') | |
end | |
end | |
end | |
end | |
end | |
require 'trimmer' | |
class ClassName < ActiveRecord::Base | |
include Trimmer | |
trimmed_fields :attributeA, :attributeB | |
end | |
# method 2 - code found on Stackoverflow | |
def clean_data | |
# trim whitespace from beginning and end of string attributes | |
attribute_names().each do |name| | |
if self.send(name.to_sym).respond_to?(:strip) | |
self.send("#{name}=".to_sym, self.send(name).strip) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment