Created
May 8, 2015 23:26
-
-
Save brainopia/ac23928a4f99758793de 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
# Usually normalization is performed during `before_validation` | |
# or in a setter. But neither would help with normalization of | |
# where conditions. | |
# | |
# This will add `normalize` to ActiveRecord with support for | |
# where conditions. For example, | |
# | |
# class User | |
# normalize(:email) { email.downcase } | |
# end | |
# User.create(email: 'foo@BAR') # creates foo@bar | |
# User.where(email: 'FOO@bar') # finds foo@bar | |
# | |
# In rails 5 it could be easily replaced with AR column type API | |
module Normalize | |
class Wrapper | |
def initialize(convertor) | |
@convertor = convertor | |
end | |
def dump(value) | |
@convertor.call value if value | |
end | |
alias load dump | |
end | |
def normalize(attribute, convertor) | |
serialize attribute, Wrapper.new(convertor) | |
end | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment