script
script

Reputation: 2167

Replace specific values in a struct with custom values

I have different structs returned from database and i want to replace the value Ecto.Assoication.Notloaded with some custom value like not loaded in all of them.

This is one record

 unit = %{
  __meta__: #Ecto.Schema.Metadata<:loaded, "units">,
  cdc_location_class_id: nil,
  description: "",
  facility: #Ecto.Association.NotLoaded<association :facility is not loaded>,
  facility_id: 2215,
  id: 719,
  is_active: true,
  name: "Unit",
  rooms: #Ecto.Association.NotLoaded<association :rooms is not loaded>
}

This is the map I want

 unit = %{
  __meta__: #Ecto.Schema.Metadata<:loaded, "units">,
  cdc_location_class_id: nil,
  description: "",
  facility: "not loaded">,
  facility_id: 2215,
  id: 719,
  is_active: true,
  name: "Unit",
  rooms: "not loaded"
}

Any suggestions?

Thanks

Upvotes: 0

Views: 502

Answers (3)

Dogbert
Dogbert

Reputation: 222388

I'd use :maps.map/2, pattern match on the value argument, and replace it as necessary:

new_unit =
  :maps.map(fn
    _, %Ecto.Association.NotLoaded{} -> "not loaded"
    _, value -> value
  end, unit)

If you need to run this on a list of maps, just put the above in a function and use Enum.map/2.

Upvotes: 1

Lucas Franco
Lucas Franco

Reputation: 382

You can try something like this:

unit = %{
  __meta__: #Ecto.Schema.Metadata<:loaded, "units">,
  cdc_location_class_id: nil,
  description: "",
  facility: #Ecto.Association.NotLoaded<association :facility is not loaded>,
  facility_id: 2215,
  id: 719,
  is_active: true,
  name: "Unit",
  rooms: #Ecto.Association.NotLoaded<association :rooms is not loaded>
}

unit = case Ecto.assoc_loaded?(unit.facility) do
  false -> Map.put(unit, :facility, "not loaded")
  _ -> unit
end

Upvotes: 0

chris
chris

Reputation: 2863

since structs are just maps, they work with the functions from the Map module

So you can use Map.put to replace the value. Here is the example:

defmodule Test do
  defmodule User do
    defstruct name: "John", age: 27
  end

  def test() do
    a = %User{}
    IO.inspect a
    a = Map.put(a, :name, "change")
    IO.inspect a
  end

end

Test.test()

Upvotes: 0

Related Questions