Skip to content

Instantly share code, notes, and snippets.

@Sutto
Forked from thomasfedb/cleaner.rb
Created December 30, 2010 08:37
Show Gist options
  • Save Sutto/759599 to your computer and use it in GitHub Desktop.
Save Sutto/759599 to your computer and use it in GitHub Desktop.
module AttrCleaner
module ModuleMixin
def self.included(base)
base.class_eval do
extend ClassMethods
alias_method_chain :write_attribute, :cleaner
end
end
module ClassMethods
@@attr_cleaners = []
def write_attribute_with_cleaner(attr_name, value)
if @@attr_cleaners.include?(attr_name.to_sym) && value.is_a?(String)
# Don't modify in place since we don't control it's origin.
value = value.strip
value = nil if value.empty?
end
write_attribute_without_cleaner(attr_name, value)
end
def attr_cleaner(*args)
only = Array(args[:only])
except = Array(args[:except])
columns = column_names.map(&:to_sym) & only
@@attr_cleaners = columns - except
end
end
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment