Skip to content

Instantly share code, notes, and snippets.

@brainopia
Created May 8, 2015 23:26
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save brainopia/ac23928a4f99758793de to your computer and use it in GitHub Desktop.
Save brainopia/ac23928a4f99758793de to your computer and use it in GitHub Desktop.
# 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