0
votes

I'm writing some get helpers in my Phoenix web app. In rails, you would generally name (or have method missing) helpers like find_account_by_email(email), etc.

With pattern matching seeming so core to Elixir/Erlang, I'm wondering if I'm better of writing my helpers like:

def get_account({email: email}) do
  # ...
end

Phoenix stubs out a get_account(id) method, so it feels to me that reusing the name with pattern matching is more idiomatic?

1

1 Answers

4
votes

Welcome to Stack Overflow!

While might be called the "Rails for Elixir", the design patterns and the architecture considerations are very different. Exposing random functions that "might be used for a bunch of things" isn't really part of the philosophy.


But the good part is, that if your use-case does call for something like this, it's very easy to extend existing functionality using Macros, Behaviours or Protocols. For your simple use-case, you can indeed create a generic method (or a set of methods), but I would lose the tuple:

defmodule Account do
  def get(clauses) do
    Repo.get_by(Account, clauses)
  end
end

You can call it using:

Account.get(email: "[email protected]")

But I would argue if replacing one one-liner with another, truly added enough value to your codebase to warrant it.


Side Note: I actually created a library to add Rails-style model helpers to Ecto schemas in Elixir apps to ease-in Rails developers to Phoenix, exposing methods similar to what active-record does. Also see the note about complex queries.