-
-
Save Sutto/759599 to your computer and use it in GitHub Desktop.
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
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