I have Userone that has an attribute String email. However, when I do email in my application, I find it advisable to first convert it to an object (not persistent) email, for example:
class User < ActiveRecord::Base
def email
Email.new(self.read_attribute :email)
end
end
Email#to_sand are Email#to_strdefined as just the source string (for example, foo@bar.com), so it is usually pretty transparent to the client regardless of whether they deal with emailor String,
This works great when assigning attributes with ActiveRecord:
> email = Email.new('foo@bar.com')
> user.email = email
ActiveRecord knows that the attribute emailis a string and transforms the object accordingly email. A little puzzling, this is not done when querying the database:
> email = Email.new('foo@bar.com')
> User.find_by email: email
ActiveRecord::StatementInvalid: can't cast Email to string
,
> User.find_by email: email.to_s
?