Intercept find_by_attribute method active record
-
18-04-2021 - |
Question
I have a model that has a cellphone
Cellphones are store using a particular format in the database. I'd like to intercept User.find_by_cellphone("1234567890") and normalize the cellphone, then call the "real" find_by_cellphone("123-456-7890").
How would I go about that? I was thinking of renaming find_by_cellphone to ar_find_by_cellphone then overwrite find_by_cellphone and call ar_find_by_cellphone in it. Any other ideas?
La solution
There actually isn't a method named find_by_cellphone
, this is just ActiveRecord magically using Ruby's method_missing
to dynamically do this for you.
To do what you want, just define find_by_cellphone
as a class method in your Cellphone
class and it'll use this rather than the built-in one:
def self.find_by_cellphone(number)
normalized_number = ... # normalize your number
self.where(:cellphone => normalized_number).first
end