lejoko
Standard String representation for entities - what is the Elixir way of replacing Ruby's to_s() method?
Hi,
I’m currently learning Phoenix. In my Rails apps, I always define a to_s() method on each and everyone of my ActiveRecord classes. That allows me to build strings anywhere in my apps that look like "The entity #{my_entity_var} has been processed successfully" that are automatically rendered as “the entity Output Of to_s() Method has been processed successfully”.
Is there a standard Phoenix or Elixir way of defining a custom string representation for Ecto entities or, more generally, for Structs ? What is the “best practices” way of doing something like that ?
Thanks in advance.
Marked As Solved
axelson
It sounds like you want to implement the String.Chars protocol: String.Chars — Elixir v1.20.2
Here’s some info on protocols: https://elixir-lang.org/getting-started/protocols.html
Also Liked
LostKobrakai
That, but also if this should indeed be a global concept I’d still use a protocol, but your own instead of String.Chars. Somethings like MyApp.HumanizedIdentityString.to_string/1. That can be used in your presentation layer (like described before) to replace placeholders in your validation errors.
lejoko
It is my first question here and the quality of the discussion and of the answers is staggering! Thanks to all those who answered!
benwilson512
Got it. And I think this gets to the crux of the matter: In general the Elixir community thinks that it is very important to be explicit about such things. How to refer to a user varies by context. Sometimes name works, sometimes it’s employee ID, sometimes it’s username. A shipment is referred to by its order number in some cases and it’s tracking number in others.
Defaults like String.Chars create easy pathways, and people tend to default to the pathways that are easiest. As your program grows, a single canonical way won’t suffice so you’ll have several variations anyway eg: #{username(user)} vs #{short_name(user}) vs #{user} and in that last case it requires everyone to simply remember “oh right, the default is long name”. Instead it could just be #{full_name(user)} like the rest and then the code just tells you what it’s doing.
Popular in Questions
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #advent-of-code
- #elixirconf-us
- #distillery
- #processes
- #forms
- #api
- #metaprogramming
- #security
- #performance









