Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to implement setters on Ecto models (or Elixir structs)

Tags:

elixir

ecto

I'm coming from a Rails mindset and am used to adding lots of setters to ActiveRecord models to trim/lowercase strings (e.g. email addresses) or normalize phone numbers to use "-" as separators. I like the setter method because it keeps code that modifies the record DRY. Is this possible with Elixir/Ecto?

like image 465
Krut Avatar asked Dec 14 '25 09:12

Krut


1 Answers

Currently, there is no mechanism. The best you can do is to create a function like:

User.normalize(%User{}, conn.params["user"])

Right now, we are planning to move this code to custom types. So for example you implement an e-mail type that knows how to properly cast and normalize the data, and casting would work on Ecto queries and when assigning field values.

like image 118
José Valim Avatar answered Dec 16 '25 09:12

José Valim