Mr_Coffeey

Mr_Coffeey

Any alternatives for @derive and Poison.Encoder?

Hi guys!

In this moment I am working in a large umbrella application composed for around 4 applications each one has their own models that are using this implementation for Poison.Encoder

defimpl Poison.Encoder, for: Any do
    def encode(%{__struct__: App.Models.Task} = struct, options) do
    struct =
        if struct.geom do
            {lon, lat} =  struct.geom.coordinates
            %{struct | lon: lon, lat: lat}
        else
            struct
        end
        encode_model(struct, options)
    end

    def encode(%{__struct__: _} = struct, options) do
        encode_model(struct, options)
    end

    def encode({lon, lat}, options) when is_float(lon) and is_float(lat) do
        %{lon: lon, lat: lat}
        |> sanitize_map()
        |> Poison.Encoder.Map.encode(options)
    end

    defp encode_model(model, options) do
        model
        |> Map.from_struct()
        |> sanitize_map()
        |> Poison.Encoder.Map.encode(options)
    end

    defp sanitize_map(map) do
        map
        |> Enum.filter(
            fn({_, %Ecto.Association.NotLoaded{}}) -> false
            ({:__meta__, _}) -> false
            ({:__struct__, _}) -> false
            ({_, _}) -> true
           end)
    |> Map.new()
    end
end

My model looks like:

# App.Models.Task
@derive {Poison.Encoder, only: [
  :address,
  :address_extra,
  :geom,
  :country,
  :dep_state,
  :city,
  :zip_code,
  :lat,
  :lon
]}
schema "tasks" do
  field(:address, :string)
  field(:address_extra, :string)
  field(:geom, Geo.Geometry)
  field(:country, :string)
  field(:dep_state, :string)
  field(:city, :string)
  field(:zip_code, :string)
  field(:lat, :float, virtual: true)
  field(:lon, :float, virtual: true)
  
  belongs_to(:service, App.Models.Service)
  timestamps()
end

This obviously doesn’t work once I want to compile my releases (using distillery) since I’m overriding the existing encoder implementations. So, in order to fix the issue I will need to implement Poison.Encoder using @derive in my models.

So the thing is, I know preloading the relationships is the way to go, but, what if I don’t want to preload all the relationships of my models? There are another way to go? If this is the only way, at least can I skip preloading relationships?

Thank you so much in advance for your time.

Marked As Solved

michalmuskala

michalmuskala

In general the protocol implementation is a bad idea for encoding domain entities like ecto structs - it’s very likely you’d like to differ how you encode them in different situations and protocols are global.

The way to go is to use phoenix views to translate from structs to simple data that can be encoded - take a look at the default code phoenix generates when you use phx.gen.json.

Where Next?

Popular in Questions Top

_russellb
I want to try my hand at web scraping. What tools/libraries do I need to use. I’m hoping to turn this into something professional so don’...
New
New
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 l...
New
lastday4you
I wanted to check elixir version in phoenix because i found that my elixir is 1.5 but when i use Enum.chunk_by it said the function is un...
New
chrisalley
ExUnit now has describe blocks which is a welcome addition coming from RSpec. In the docs, it states that nested hierarchies of describe ...
New
electic
Hi, I am new to Elixir. I am trying to use the DateTime component to insert a date into MySQL however the there seems to be no way to fo...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
bsollish-terakeet
Credo is smart enough to check for (something like) this: assert length(the_list) == 0 with this response: Checking if an enum is empt...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call t...
New
svb
Hi! Currently I want to submit a form by pressing the Enter key. However, since my input field is of type “textarea” this is just adds a...
New

Other popular topics Top

sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 42920 311
New
JorisKok
I have a server on AWS, and was running a load test using artillery. When looking at the Phoenix dashboard I see the Ports going to 100% ...
New
josevalim
Hi everyone, One of the features added to Elixir early on to help integration with Erlang code was the idea of overridable function defi...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a > b) do {:ok, "a"} end if (a < b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New
gausby
I asked this very same question on twitter and got some interesting feedback, but I thought it would be a good question to ask here as we...
1207 39297 209
New
saif
Hello everyone, Long time lurker first time poster here. I’ve recently begun working on Elixir full-time again! :raised_hands: It’s been...
New
AstonJ
Seen any cool LiveView demos, sample apps or examples? Please post them here! :003:
New
dogweather
I wrote this comment on r/haskell, and it’s not popular there. :wink: But I think I’m on to something… Haskell reminds me of Java, and e...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New

Latest on Elixir Forum

We're in Beta

About us Mission Statement