Help in understanding code that always matches

Hi,

I am trying to learn Elixir by reading articles and code.

I cam across this code, which I am not able to understand.
It is taken from here: https://github.com/ueberauth/guardian

defmodule MyApp.Guardian do
  use Guardian, otp_app: :my_app

  def subject_for_token(resource, _claims) do
    sub = to_string(resource.id)
    {:ok, sub}
  end
  def subject_for_token(_, _) do
    {:error, :reason_for_error}
  end

  def resource_from_claims(claims) do
    id = claims["sub"]
    resource = MyApp.get_resource_by_id(id)
    {:ok,  resource}
  end
  def resource_from_claims(_claims) do
    {:error, :reason_for_error}
  end
end

The first subject_for_token function should pattern match any call with 2 parameters. So, why do we need the other one with underscores?

Similarly, why do we need second resource_from_claims function.

Thanks!

It is true it is always matched by first clause. To make it useful, You can add a guard clause or a better matching pattern. Like…

def subject_for_token(%{} = resource, _claims) do

or

def subject_for_token(resource, _claims) when is_map(resource) do

Same applies for second function.

BTW If You compile this code, You will get warnings

iex)> recompile()
==> next_web
Compiling 1 file (.ex)
warning: this clause cannot match because a previous clause at line 4 always matches
  lib/next_web/guardian.ex:8

warning: this clause cannot match because a previous clause at line 12 always matches
  lib/next_web/guardian.ex:17
2 Likes

Thank you for great explanation!

In hindsight, I should have tried compiling the code :slight_smile:

1 Like