Pattern match function with map attribute value in Enum?

  defp render_public_payload(%{"type" => "audio"} = post) do
    DB.Search.Post.public_payload(post)
  end

  defp render_public_payload(%{"type" => "onDemand"} = post) do
    DB.Search.Post.public_payload(post)
  end

  defp render_public_payload(%{"type" => "photo"} = post) do
    DB.Search.Post.public_payload(post)
  end

  defp render_public_payload(%{"type" => "text"} = post) do
    DB.Search.Post.public_payload(post)
  end

  defp render_public_payload(%{"type" => "video"} = post) do
    DB.Search.Post.public_payload(post)
  end

  defp render_public_payload(%{"type" => "livestream"} = post) do
    DB.Search.Post.public_payload(post)
  end

Is there a way for me to simplify this code by pattern matching that `type is in a possible Enum of string values? How would you recommend I clean up these very similar functions?

# TODO: give this a better name
@types ["audio", "onDemand", "photo", "text", "video", "livestream"]
defp render_public_payload(%{"type" => type} = post) when type in @types do
  DB.Search.Post.public_payload(post)
end
4 Likes

@sergio Sure, it’s really easy:

  @types ["audio", "livestream", "onDemand", "photo", "text", "video"]

  defp render_public_payload(%{"type" => type} = post) when type in @types do
    DB.Search.Post.public_payload(post)
  end

@benwilson512 sorry, did not noticed your response :smile:

4 Likes

I was attempting:

render_public_payload(post) when post["type"] in @types do

And that was giving me a cannot invoke Access.get in guard clause error. Forgot I could take it out in the pattern match itself woops

1 Like