elt547
I have a struct representing a session request with only two fields, email and bytes. Basically the struct should either be passed around as immutable or created with a default value as a function return value. I have a function random_bytes which I want to be the default value of bytes.
Since you can’t declare it like this:
defstruct [:email, bytes: random_bytes()]
Someone suggested making a “new” function:
def new(email) do
%__MODULE__{email: email, bytes: random_bytes()}
end
But to me this feels very non-idiomatic. It feels like shoehorning an object oriented pattern into a functional language.
What is the best way to build a strict with a complex default value in elixir?
Trending in Questions
I’m working on a project that simulates the bumbl example in the programming phoenix book. It acts almost like an email client. We have a...
New
Hello,
I know there is an approach for handling lists that allows for optimized traversal, but I can’t recall the specific method (somet...
New
I’m seeing that a list inside a Kino.DataTable will be interpreted as a charlist, even if the Kino.configure() is set to charlists: :as_l...
New
So my question is quite simple and i have found no conclusive answer on forum, google or AI.
Should we use :erlang.float for Integer to ...
New
Documentation
While reading the Scoped Routes section, I noticed that the documentation currently refers to a problem without explainin...
New
Hi, I’ve just set up an application with ash_authentication. There is only magic link strategy for now, so there is no confirmation add o...
New
If a change or preparation module uses Ash.Changeset.get_argument/2 or Ash.Query.get_argument/2 (or any of the other get_argument functio...
New
Other Trending Topics
I am happy to introduce the very α version of the new programming language compiled to BEAM.
Welcome Cure.
It has literally three kille...
New
Hi there! We created Gust: A task orchestrator inspired by Airflow.
For those who have never heard about Aiflow, it’s a Python-based wor...
New
Beam Bots (or just BB for short) is a framework for building fault-tolerant robotics applications in Elixir using familiar OTP patterns. ...
New
Xamal is a deployment tool for Elixir apps that deploys native releases to bare metal servers over SSH. It’s a port of GitHub - basecamp/...
New
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
With AI doing more of the implementation work, I’ve been wondering how much coding I should deliberately keep doing myself.
My main conc...
New
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #library
- #deployment
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #elixirconf
- #channels
- #exunit
- #discussion
- #code-sync
- #podcasts
- #javascript
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixirconf-us
- #ai
- #blog-post
- #elixir-ls
- #phoenix_html
- #iex
- #graphql
- #genstage
- #websockets
- #supervisor
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #hex
- #security
- #metaprogramming










Showing Posts 20 to 11- Show Best Posts
- Show All (oldest first)
- Show All (newest first)
sodapopcan
I personally don’t think this would be nice as it would mean coming across a wild
%Foo{}means there could be side-effects. I’m perfectly happy with status quo where%Foo{}means “static thing I’m allow to manipulate” andFoo.new()means “I’m special, please let me construct myself!”.cjbottaro
I was trying to say “this is an example of what OP was asking for”. It doesn’t work, but it would be nice if it did.
ycherniavskyi
Your example does not compile
(I have fixed some compile errors already):
cjbottaro
I think the post is really about “struct default values that are determined at runtime”…
Which admittedly would be kinda nice…
al2o3cr
Quick note: 99% of the time when you write
structyou really meanstruct!becausestruct!will raise if required keys from@enforce_keysare omittedstruct!will raise if given keys that aren’t allowed in the structAnother pattern that can catch bad keys at compile-time: use a struct literal combined with a function to apply defaults. Something like:
This is a little over-abstracted for the case where
SessionRequestonly has one field supplied by the user, but would make more sense if there were a dozen:integer(). It will NOT catch misconfigured use ofstruct/struct!cjbottaro
I felt this way too until I divorced the word
newfrom “object instantiation”.I think the official Elixir documentation even says…
Just use data directly:
If that’s not good enough, make a function:
And finally… metaprogramming (no example…
).
See the “In other words:” part of this section:
tomkonidas
We can even mix and match both solutions:
tomkonidas
The thing is
attrsis anEnumerable.t(), so it can be a map or a keyword. So that is why i do it after i create the struct.But yea very valid if you want to have the two functions as you showed
msimonborg
Another option would be to just build the default opts with
Keyword.put_new_lazy/3. Then you create the struct once without needing to update it, and you still only run therandom_bytes()generator when necessary. I don’t know how this would compare performance-wise with thewithstatement plus the update.I always use
__MODULE__just in case I want to change the module name down the line, I don’t have to update anything else in that file.tomkonidas
It can also be done as a
caseif you are more comfortable with that.