├── config └── config.exs ├── test ├── test_helper.exs └── maybe_test.exs ├── .formatter.exs ├── .travis.yml ├── CHANGELOG.md ├── bin ├── docs ├── setup ├── test └── release ├── mix.lock ├── .gitignore ├── README.md ├── mix.exs ├── LICENSE └── lib └── maybe.ex /config/config.exs: -------------------------------------------------------------------------------- 1 | use Mix.Config 2 | -------------------------------------------------------------------------------- /test/test_helper.exs: -------------------------------------------------------------------------------- 1 | ExUnit.start() 2 | -------------------------------------------------------------------------------- /.formatter.exs: -------------------------------------------------------------------------------- 1 | # Used by "mix format" 2 | [ 3 | inputs: ["mix.exs", "{config,lib,test}/**/*.{ex,exs}"] 4 | ] 5 | -------------------------------------------------------------------------------- /test/maybe_test.exs: -------------------------------------------------------------------------------- 1 | defmodule MaybeTest do 2 | use ExUnit.Case 3 | 4 | doctest Maybe, import: true 5 | end 6 | -------------------------------------------------------------------------------- /.travis.yml: -------------------------------------------------------------------------------- 1 | language: elixir 2 | cache: 3 | directories: 4 | - $HOME/.mix 5 | elixir: 6 | - 1.6.1 7 | otp_release: 8 | - 20.1 9 | script: 10 | - bin/test -------------------------------------------------------------------------------- /CHANGELOG.md: -------------------------------------------------------------------------------- 1 | # Change Log 2 | 3 | 4 | 5 | \* *This Change Log was automatically generated by [github_changelog_generator](https://github.com/skywinder/Github-Changelog-Generator)* -------------------------------------------------------------------------------- /bin/docs: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # Generate and open docs in your browser 4 | mix docs || { echo 'Docs were not generated!'; exit 1; } 5 | open doc/index.html || { echo 'Docs did not open'; exit 1; } -------------------------------------------------------------------------------- /bin/setup: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | 3 | mix deps.get || { echo "Dependencies did not download!"; exit 1; } 4 | echo "Running tests to confirm everything is fine..." 5 | bin/test || { echo "Tests failed"; exit 1; } -------------------------------------------------------------------------------- /mix.lock: -------------------------------------------------------------------------------- 1 | %{ 2 | "earmark": {:hex, :earmark, "1.2.4", "99b637c62a4d65a20a9fb674b8cffb8baa771c04605a80c911c4418c69b75439", [:mix], [], "hexpm"}, 3 | "ex_doc": {:hex, :ex_doc, "0.18.2", "993e0a95e9fbb790ac54ea58e700b45b299bd48bc44b4ae0404f28161f37a83e", [:mix], [{:earmark, "~> 1.1", [hex: :earmark, repo: "hexpm", optional: false]}], "hexpm"}, 4 | } 5 | -------------------------------------------------------------------------------- /bin/test: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env bash 2 | # 3 | # Test Script 4 | # 5 | # Runs tests the same way that it will be tested on CI. This is convenient 6 | # for testing your changes before you push them up for CI. 7 | 8 | MIX_ENV=test mix format --check-formatted || { echo "Code was not formatted! Please format using `mix format`."; exit 1; } 9 | MIX_ENV=test mix deps.get || { echo "Dependencies could not be fetched!"; exit 1; } 10 | MIX_ENV=test mix compile --force --warnings-as-errors || { echo "Please fix all compiler warnings!"; exit 1; } 11 | MIX_ENV=test mix docs || { echo "Docs did not compile!"; exit 1; } 12 | mix test || { echo "Tests failed!"; exit 1; } -------------------------------------------------------------------------------- /.gitignore: -------------------------------------------------------------------------------- 1 | # Elixir Language Server 2 | /.elixir_ls/ 3 | 4 | # The directory Mix will write compiled artifacts to. 5 | /_build/ 6 | 7 | # If you run "mix test --cover", coverage assets end up here. 8 | /cover/ 9 | 10 | # The directory Mix downloads your dependencies sources to. 11 | /deps/ 12 | 13 | # Where 3rd-party dependencies like ExDoc output generated docs. 14 | /doc/ 15 | 16 | # Ignore .fetch files in case you like to edit your project deps locally. 17 | /.fetch 18 | 19 | # If the VM crashes, it generates a dump, let's ignore it too. 20 | erl_crash.dump 21 | 22 | # Also ignore archive artifacts (built via "mix archive.build"). 23 | *.ez 24 | 25 | # Ignore package tarball (built via "mix hex.build"). 26 | maybe-*.tar 27 | 28 | -------------------------------------------------------------------------------- /bin/release: -------------------------------------------------------------------------------- 1 | #!/usr/bin/env ruby 2 | 3 | puts "What version number do you want to release?" 4 | print "> " 5 | version = gets.gsub(/\n/, "") 6 | 7 | continue = system "github_changelog_generator" 8 | continue = system "git add ." 9 | continue = system "git commit -am \"Release version #{version}\"" if continue 10 | continue = system "git tag v#{version}" if continue 11 | continue = system "git push" if continue 12 | continue = system "git push -f origin v#{version}" if continue 13 | continue = system "mix hex.publish" if continue 14 | continue = system "github_changelog_generator" 15 | continue = system "git add ." if continue 16 | continue = system "git commit -am \"Update changelog for version #{version}\"" if continue 17 | continue = system "git push" if continue 18 | 19 | puts "Version #{version} was successfully released!" -------------------------------------------------------------------------------- /README.md: -------------------------------------------------------------------------------- 1 | # Maybe 2 | [![Hex.pm](https://img.shields.io/hexpm/v/maybe.svg)](https://hex.pm/packages/maybe) 3 | [![Build Status](https://travis-ci.org/infinitered/maybe.svg?branch=master)](https://travis-ci.org/infinitered/maybe) 4 | 5 | Access nested Elixir maps and structs, protected from `nil`. Somewhat similar to "Optionals" in Apple Swift. 6 | 7 | ```elixir 8 | import Maybe 9 | 10 | info = %{city: %{name: "Portland"}} 11 | maybe(info.city.name) 12 | # => "Portland" 13 | 14 | map = %{} 15 | maybe(map.city.name) 16 | # => nil 17 | ``` 18 | 19 | See the original [forum post](https://elixirforum.com/t/maybe-nil-protection-for-nested-structs/468) for 20 | more an explanation of the problem this package solves. 21 | 22 | ## Installation 23 | 24 | Add `maybe` to your list of dependencies in `mix.exs`: 25 | 26 | ```elixir 27 | def deps do 28 | [ 29 | {:maybe, "~> 1.0.0"} 30 | ] 31 | end 32 | ``` 33 | 34 | See [the documentation](https://hexdocs.pm/maybe) for more details. -------------------------------------------------------------------------------- /mix.exs: -------------------------------------------------------------------------------- 1 | defmodule Maybe.MixProject do 2 | use Mix.Project 3 | 4 | def project do 5 | [ 6 | app: :maybe, 7 | description: "Nil protection for nested maps and structs", 8 | version: "1.0.0", 9 | elixir: "~> 1.4", 10 | start_permanent: Mix.env() == :prod, 11 | deps: deps(), 12 | docs: docs(), 13 | package: package() 14 | ] 15 | end 16 | 17 | def application do 18 | [ 19 | extra_applications: [:logger] 20 | ] 21 | end 22 | 23 | def package do 24 | [ 25 | maintainers: ["Daniel Berkompas"], 26 | licenses: ["MIT"], 27 | links: %{ 28 | "GitHub" => "https://github.com/infinitered/maybe" 29 | }, 30 | source_url: "https://github.com/infinitered/maybe" 31 | ] 32 | end 33 | 34 | defp docs do 35 | [ 36 | main: Maybe 37 | ] 38 | end 39 | 40 | defp deps do 41 | [ 42 | {:ex_doc, ">= 0.0.0", only: [:dev, :test]} 43 | ] 44 | end 45 | end 46 | -------------------------------------------------------------------------------- /LICENSE: -------------------------------------------------------------------------------- 1 | MIT License 2 | 3 | Copyright (c) 2018 Infinite Red, Inc. 4 | 5 | Permission is hereby granted, free of charge, to any person obtaining a copy 6 | of this software and associated documentation files (the "Software"), to deal 7 | in the Software without restriction, including without limitation the rights 8 | to use, copy, modify, merge, publish, distribute, sublicense, and/or sell 9 | copies of the Software, and to permit persons to whom the Software is 10 | furnished to do so, subject to the following conditions: 11 | 12 | The above copyright notice and this permission notice shall be included in all 13 | copies or substantial portions of the Software. 14 | 15 | THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR 16 | IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, 17 | FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE 18 | AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER 19 | LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, 20 | OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE 21 | SOFTWARE. 22 | -------------------------------------------------------------------------------- /lib/maybe.ex: -------------------------------------------------------------------------------- 1 | defmodule Maybe do 2 | @moduledoc """ 3 | Access nested maps and structs, protected from `nil`. 4 | 5 | See `maybe/1` or `maybe/2` for more details. 6 | 7 | ## Example 8 | 9 | import Maybe 10 | 11 | map = %{city: %{name: "Portland"}} 12 | maybe(map, [:city, :name]) # => "Portland" 13 | maybe(map.city.name) # => "Portland" 14 | maybe(map.city.location) # => nil 15 | 16 | """ 17 | 18 | @doc """ 19 | Get a value out of a nested map or struct, or return nil. 20 | 21 | Compiles down to `maybe/2`. In other words, this: 22 | 23 | maybe(map.city.name) 24 | 25 | Is compiled down to a simple function call to `maybe/2`: 26 | 27 | maybe(map, [:city, :name]) 28 | 29 | ## Examples 30 | 31 | iex> map = %{city: %{name: "Portland"}} 32 | ...> maybe(map.city.name) 33 | "Portland" 34 | 35 | iex> map = %{city: nil} 36 | ...> maybe(map.city.name) 37 | nil 38 | """ 39 | defmacro maybe(ast) do 40 | [variable | keys] = extract_keys(ast) 41 | 42 | quote do 43 | maybe(var!(unquote(variable)), unquote(keys)) 44 | end 45 | end 46 | 47 | @doc """ 48 | Get a value out of a nested map or struct, or return nil. 49 | 50 | For prettier syntax, see the `maybe/1` macro. 51 | 52 | ## Examples 53 | 54 | iex> map = %{city: %{name: "Portland"}} 55 | ...> maybe(map, [:city, :name]) 56 | "Portland" 57 | 58 | iex> maybe(%{}, [:city, :name]) 59 | nil 60 | """ 61 | @spec maybe(map, keys :: [atom]) :: any | nil 62 | def maybe(map, keys) 63 | def maybe(nil, _keys), do: nil 64 | def maybe(val, []), do: val 65 | 66 | def maybe(map, [h | t]) do 67 | maybe(Map.get(map, h), t) 68 | end 69 | 70 | defp extract_keys(ast, keys \\ []) 71 | defp extract_keys([], keys), do: keys 72 | 73 | defp extract_keys({{:., _, args}, _, _}, keys) do 74 | extract_keys(args, keys) 75 | end 76 | 77 | defp extract_keys([{{:., _, args}, _, _} | t], keys) do 78 | keys = keys ++ extract_keys(args) 79 | extract_keys(t, keys) 80 | end 81 | 82 | defp extract_keys([{:., _, args} | t], keys) do 83 | keys = keys ++ extract_keys(args) 84 | extract_keys(t, keys) 85 | end 86 | 87 | defp extract_keys([key | t], keys) do 88 | keys = keys ++ [key] 89 | extract_keys(t, keys) 90 | end 91 | end 92 | --------------------------------------------------------------------------------