7rans

7rans

Update shorthand for Access behavor

I implemented Access behavior for a struct today. Pseudo-code…

defmodule MyStruct do
  defstruct data: %{}
  @behaviour Access
   # ... implementation of Access behavior on `data` ...
end

Then I tried:

  a = %{x: 1, y: 2}
  s = %MyStruct{data: a}
  z = %MyStruct{ s | y: 3 }

And of course it did not work.

Sure would be awesome if it could be made to work somehow though.

Most Liked

cmo

cmo

The way to achieve that is to have two function heads, one that matches on the struct and one that matches on the changeset. You can have the calculate logic in a separate private function and just extract the fields and put the result into whatever structure in each of the function heads.

And where are you going to get the other values for the calculation, if they’re not being passed as args? Passing required arguments to functions is not an antipattern :wink:

LostKobrakai

LostKobrakai

I think one thing is missing from this discussion and that‘s the notion of violating DRY by having ways to calculate the computed value from various sources of data. Instead of trying to avoid repetition by limiting the number of inputs (only struct or only changeset) you can also keep both inputs, but delegate the business logic in question to a shared helper.

def with_computed(%Ecto.Changeset{} = cs) do
  a = get_field(cs, :a)
  b = get_field(cs, :b)
  put_change(cs, :x, compute_x(a, b))
end

def with_computed(%Struct{} = struct) do
  %{struct | x: compute_x(struct.a, struct.b)}
end

defp compute_x(a, b), do: a + b
sodapopcan

sodapopcan

As @D4no0 said, it really sounds like you are trying to create class-like code. The problem with the code you showed us is that it just doubles down on why you think you need access. The real question is: “Why do you need a function that works on both in the first place?” The reason people are questioning you is because there shouldn’t be any reason to need to manually update a key of a schema’s struct, all changes should be done through changesets.

No such thing! Changeset constructors can look however you need to them to. The fact that cast_assoc will automagically look for a changeset/2 function is just a convenience. I won’t name names (@dimitarvp :sweat_smile:) but some people think this in-of-itself is a mistake and the :with option should always be used. Which is just a lot of words to try and re-enforce my point.

sodapopcan

sodapopcan

I used to feel this way! I definitely came around to them. I usually just use put_assoc for tenant-like relationships, or really just anything I don’t want the user to have control over changing, otherwise I just cast the ids directly. And I came to love cast_assoc for many types of nested relationships, but not all! But ya, we don’t have to get into this in this thread :sweat_smile:

D4no0

D4no0

It is absolutely not clear what you want to do, can you show a extensive example that involves ecto changesets?

Or maybe the problem could be reformulated, it is often the case that you will try to do things the way you were used to in other languages.

Where Next?

Popular in Proposals: Ideas Top

martosaur
TL;DR Logger.Translator acts as a global filter and swallows structure of some OTP reports, which some logger handlers could benefit from...
New
rekkice
I’m building an editor integration to evaluate Elixir code in an IEx session. While Code.eval_string/3 allows tracking variable bindings,...
New
kip
Sumary of proposal DateTime.from_iso8601/3 adjusted to: set all numeric fields to the values as parsed (not shifted to UTC), preservi...
New
tristan
This is a cross post from the Erlang Forums. ETS table `select_take` - Proposals: Ideas - Erlang Programming Language Forum - Erlang Foru...
New
MeerKatDev
many times we do stuff like (e.g. test setups, json views in phoenix) aaa = ... bbb = ... ccc = ... %{aaa: aaa, bbb: bbb, ccc: ccc} and...
New
cevado
Being able to build nested relations in a schemaless changeset would be helpful to deal with complex forms on Phoenix without the need to...
New
pdgonzalez872
Hi! There has been some discussion about hiring/jobs on here and I thought about running this by everyone. I wanted to try to help recr...
New
dli
Ecto currently supports some data-modifying WITH statements / CTEs for Postgres: Options: […] :operation - one of :all , :update_all ,...
New
cevado
IEx is a very powerfull shell and it would be awesome to have all this power integrated inside a code editor. Clojure enables something l...
New
dkuku
This is a proposal to make the map key mismatch errors a bit better: Every time I have a typo It’s very challenging for me even when I u...
New

Other popular topics Top

William
I would like to know that is there any online source for learning Phoenix Framework for building E-Commerce Store? Any advantage on build...
New
lessless
I believe there are people here who are dealing with CSV files import on the daily basis, and since Excel is a really popular tool there ...
New
gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
openscript
Hello! Sorry for this astonishing simple question, but I’m really stuck. I try to set up the intellij-elixir plugin, but I don’t know ho...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
Jim
As a follow up to my earlier question: I have the code compiling and running but not getting a successful login from the rest server. ...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
rms.mrcs
Hi, I need to transform a list of numbers into a map where the keys are the indexes and the values are the original values of the list....
New
alice
Hey, Just curious what are the main benefits of Elixir compared to Clojure? When is Elixir more useful than Clojure and vice versa? Th...
New
qwerescape
Is there a way to get the call stack or stack trace at any point in the code? Not from exceptions, but an expression that returns how the...
New

We're in Beta

About us Mission Statement