Skip to content

Instantly share code, notes, and snippets.

@thomasfedb
Created December 30, 2010 08:13
Show Gist options
  • Save thomasfedb/759584 to your computer and use it in GitHub Desktop.
Save thomasfedb/759584 to your computer and use it in GitHub Desktop.
module AttrCleaner
module ModuleMixin
extend ActiveSupport::Concern
included do
alias_method_chain :write_attribute, :cleaner
class_attribute :attr_cleaners
end
module ClassMethods
def write_attribute_with_cleaner(attr_name, value)
if attr_cleaners.include?(attr_cleaners.to_sym) && value.is_a?(String)
value = value.strip
value = nil if value.empty?
end
write_attribute_without_cleaner(attr_name, value)
end
def attr_cleaner(*args)
all_columns = column_names.map(&:to_sym)
only = Array(args[:only])
except = Array(args[:except])
columns = only.empty? ? all_columns : (only & all_columns)
self.attr_cleaners = (Array(self.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