Skip to content

Instantly share code, notes, and snippets.

@slashdotdash
Last active September 19, 2022 23:02
Show Gist options
  • Star 7 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save slashdotdash/70541f4e79d17bcd238a9a6adf7383b8 to your computer and use it in GitHub Desktop.
Save slashdotdash/70541f4e79d17bcd238a9a6adf7383b8 to your computer and use it in GitHub Desktop.
Elixir tips

Elixir tips

Editor

Style guide

When dealing with lists, maps, structs, or tuples whose elements span over multiple lines and are on separate lines with regard to the enclosing brackets, it's advised to use a trailing comma even for the last element:

[
  :foo,
  :bar,
  :baz,
]

Best practices

Umbrella projects

Use umbrella projects to split a codebase into smaller applications. Mix has support for referencing an umbrella app as a dependency in your mix.exs config file.

defp deps do
    [
      {:another_app, in_umbrella: true, path: "../another_app"}
    ]
end

Mix tasks

Display outdated packages

mix hex.outdated --all

Update dependencies

mix deps.get
mix deps.update --all

Testing

Using tags

Apply an @tag :wip tag to a test to limit test runs to only tests that are being developed.

mix test --only wip

You can apply multiple tags to a single test.

@tag :integration
@tag :database
test "an example test" do
  ...
end
mix test --only unit --only integration --exclude database

Include test helpers

Include elixirc_paths in the application mix.exs file. This is configured by mix environment so you can set additional paths to include.

defmodule Example.Mixfile do
  use Mix.Project

  def project do
    [
      app: :example,
      version: "0.0.1",
      elixir: "~> 1.2",
      elixirc_paths: elixirc_paths(Mix.env),
      # ...
    ]
  end

  defp elixirc_paths(:test), do: ["lib", "test/helpers"]
  defp elixirc_paths(_), do: ["lib"]
end

Logging

Use function argument when using Logger to log so the message string is not interpolated if the log level is configured to ignore given level.

Logger.debug(fn -> "logging about #{inspect data}" end)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment