9mm

9mm

I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a loss how to do this without an if statement. I also don’t know if rebinding the same variable is a ‘code smell’

data = %{
  requireInteraction: true,
  title: title,
  icon: icon,
  click_action: click_action
}

if body do
  data = Map.put(data, :body, body)
end

Showing Posts 1 to 10

9mm

9mm OP

It also warns me of this. So confusing :s

Note variables defined inside case, cond, fn, if and similar do not leak. If you want to conditionally override an existing variable “data”, you will have to explicitly return the variable. For example:

MrDoops

MrDoops

So you want to update the body key value pair to the data map when the body key exists?

9mm

9mm OP

I just want to add the :body key/value pair into the json blob if the body variable isnt nil. Im’ sending a message, and body is optional, but I can’t send NULL in the json or it literally puts a blank space.

MrDoops

MrDoops

You can use Map.has_key?(data, :body) with a case statement. A more Elixir way might be to pattern match on the presence or absence of the map.

def process(%{body: _} = data), do: data
def process(%{} = data), do: %{data | body: nil}
9mm

9mm OP

Is there a way that doesnt require creating methods to do it? I suppose I could do that, i feel like my module will get cluttered very fast if i have so many methods to do something like that

How would the case statement look?

9mm

9mm OP

This has got to be the most frustrating day coding since i learned ruby like 10 years ago JESUS CHRIST.

I have spent 3 hours just trying to get a stupid map to update

Here is what i had so far

data =
  Enum.reject(
    %{
      requireInteraction: true,
      title: title,
      body: body,
      icon: icon,
      click_action: click_action
    },
    &(!elem(&1, 1))
  )
9mm

9mm OP

damnit it converts it to a list… this gives me so much of a headache. i have never been stuck on such easy stuff in so long, this is by far the hardest coding day in LONG TIME

WolfDan

WolfDan

Imo this is a elixir way as well to do it:

data = %{
  requireInteraction: true,
  title: title,
  icon: icon,
  click_action: click_action
}

data =
    if body do
      Map.put(data, :body, body)
    else
      data
    end

personally I’d prefer to create more functions like MrDoops pointed out, you can do anonymous functions as well

9mm

9mm OP

Ok.. I guess skip all my preconceptions and just use the method way. The only problem is it doesnt remove the key it only sets it to NULL (I need to remove the key).

Eiji

Eiji

I don’t like to have two variables with same name in scope. For me such code is less readable.

If you have only one variable like that then use if or && with || instead like:

data = %{…}
updated_data = if body, do: Map.put(data, :body, body), else: data
# or
updated_data = body && Map.put(data, :body, body) || data

In case you need to do it multiple times then I recommend to do something like:

data = %{…}
data2 = %{example: 5, body: body, sample: 10}
Enum.reduce(data2, data, fn {key, value}, acc -> value && Map.put(acc, key, value) || acc)

This is equivalent for maps:

:maps.filter(fn _key, value -> not is_nil(value) end, data)

Where Next? Top

Trending in Questions Top

Blokh
Hey guys, I’ve got a huge CSV ( around 10 GB ) that needs to be processed hourly Do you guys have any suggestions what is the best prac...
New
kszambelanczyk
Hello! Could someone please give me a help/sample code, how to delete a file from s3 using waffle/waffle_ecto from Phoenix app. I creat...
New
Onor.io
I have what I’ve heard referred to as a “lookup table” in my database. This is a way of assigning codes to common values. One common lo...
New
jaybe78
Hello, I’m developing a online persistent chat system (what’s app) like using elixir/dynamodb/aws for a mobile app(flutter). The diffic...
New
Trolleger
What approach to take when sending live updates to “random” users Hi! I have a question, I have a little chat app, and when I create a DM...
New
matt-savvy
Anyone here using Honeybadger? My Honeybadger account is being overwhelmed with noise from some bots. Seeing a lot of Bandit.HTTPError...
New
RemyXRenard
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

Other Trending Topics Top

garrison
Hobbes is a low-level distributed database for the Elixir programming language. Hobbes provides a simple, safe, and scalable storage lay...
New
mcass19
ExRatatui lets you cook up rich terminal UIs in Elixir, powered by Rust’s ratatui via Rustler NIFs. Build interactive terminal applicatio...
New
Damirados
Hello everyone. After busy few months I am happy to announce v0.1.0 of Emerge & Solve. They are GUI (Emerge) and State management (S...
New
netoum
Corex is an accessible, unstyled UI component library for Phoenix that integrates Zag.js state machines using Vanilla JavaScript and Live...
New
wintermeyer
There are three potential reasons for members of this forum to have a look at https://vutuv.de You are tired or annoyed of LinkedIn. Yo...
New
webofbits
Aludel - LLM Evaluation Workbench Aludel is an embeddable Phoenix LiveView dashboard for evaluating and comparing LLM prompts across mult...
New

We're in Beta

About us Mission Statement

Options

Thread Display Mode




Thread Preview

Skip Thread Previews