jeroenbourgois

jeroenbourgois

How to extend kernel module without aliasing/importing it?

I would like to add a function to my project that is available throughout all modules without aliasing/importing it. How should I go about it? I know I can include it in my *_web.ex file so it becomes available in controllers, views, … but I want to use it in business logic as well. Like the title op my topic suggest, I would like it to be available next to all other default Kernel module functions.

The function itself is very simple:

def is_empty(""), do: true
def is_empty(nil), do: true
def is_empty([]), do: true
def is_empty(_), do: false

Thank you for your input!

PS: I opted for is_empy/1 vs empty?/1 to relate to the existing is_nil/1 function.
PS2: our codebase has various occurences of x in ["", nil] checks, which I would like to simplify.

Marked As Solved

jeroenbourgois

jeroenbourgois

Thank you (both) for the responses!

As for the data, most checks are if a in ["", nil] (without the list), because for those fields in the database we can have nil or the empty string. In the database we want the difference, since nil is the default (aka: never set) and the empty string can be ‘set to empty’, but was set none the less.

We find it valuable to have that distinction in the db, but in the application it doesn’t matter most of the time.

Thanks again for the input, I’ll take this feedack to our team!

Also Liked

christhekeele

christhekeele

Yup. Elixir is explicit about imports by design, with Kernel being the single exception. You will need to define some sort of MyProject.Kernel and import it wherever you want to use its functions.


Just BTW, the is_nil/1 function does not choose is_nil over nil? half-hazardly, this is in line with a particular Elixir naming convention:

Type checks and other boolean checks that are allowed in guard clauses are named with an is_ prefix.

Note that type checks that are not valid in guard clauses do not follow this convention. For example: Keyword.keyword?/1.

To follow this convention that other developers in your project may rely upon, you would either want to name this function empty?/1, or implement it as a guard.

That implementation will be different than the functional version, but can be used anywhere guards or allowed! To translate your example is_empty/1, it would look something like:

defmodule MyProject.Kernel do
  defguard is_empty(thing) when thing in ["", nil, []]
end

Finally, as a design note, outside of extenuating circumstances, I would treat it as a code smell that you are often checking if thing in ["", nil, []]. The implication is that you are regularly uncertain if your data is a string, list, or null value; all throughout your program.

It would be hard with no context to diagnose why this is happening or propose a better pattern, but I would keep :eyes: on this part of your code! You may find an opportunity to coerce the variable type of an input into your program into a known single type close to where it is received, then confidently refactor a lot of less-confident, unassertive code. Then theoretically you could handle “empty cases” throughout just by matching against one of "", [], or nil.

LostKobrakai

LostKobrakai

There’s nothing automatically imported besides Kernel in elixir. You either need to import explicitly or have a macro doing the import.

D4no0

D4no0

I’ve dealt with this a few times also in some legacy codebases and the best solution I found is to use custom Ecto types that know how to deal with these values, you skip the step where you have to deal manually with these kind of checks.

Where Next?

Popular in Questions Top

gshaw
What is the idiomatic way of matching for not nil in Elixir? E.g., First way: defp halt_if_not_signed_in(conn, signed_in_account) when...
New
hariharasudhan94
lets say i have a sample like a = 20; b = 10; if (a > b) do {:ok, "a"} end if (a < b) do {:ok, b} end if (a == b) do {:ok, "equa...
New
dokuzbir
I want to highlight html closing tags when i click a html tag. That works in .html files but doesnt work for html.eex templates. How can...
New
vegabook
I’m brand new to Phoenix and I have stripped one of the demo applications to the bone. I just want to get an svg up on the screen. Here i...
New
beno
I will often find my self writing things similar to: case some_value do nil -> something() "" -> something() _ -> somethi...
New
pmjoe
I have a relationship of love and hate with Elixir. Lots of things are just absolutely right, but there are some things that are kind of ...
New
lucidguppy
I have a super simple question about elixir - how would I take a file like this foo bar baz and output a new file that enumerates th...
New
srinivasu
How to handle excepions in elixir? Suppose i have A, B, C ,D, E modules. and each module has get() function. A.get() method will call t...
New
komlanvi
Hi everyone, I was playing with phoenix liveView but I run into an issue. I have a form and want to validate each input text when the te...
New
hariharasudhan94
Lets say I have map like this fetching from my database %{"_id" => #BSON.ObjectId<58eb1a7a9ad169198c3dXXXX>, "email" => ...
New

Other popular topics Top

sorentwo
Hello! tl;dr Announcing Oban, an Ecto based job processing library with a focus on reliability and historical observability. After spen...
985 42920 311
New
9mm
I am constructing a JSON object (map) and I need to conditionally set a field. I’m trying to write proper elixir-way code… and I’m at a l...
New
Harrisonl
We have an ECS cluster with 4 services, where each task joins a single cluster, via discovery ECS discovery service. Currently when I de...
New
Lily
In templates/appointment/index.html.eex: <%= for appointment <- @appointments do %> <tr> <td><%= appoi...
New
AngeloChecked
What learn first? Rust or Elixir Hi Elixir community! I’m here because i want learn a new language. I’m a junior developer and mainly i ...
New
vrod
I am using the Starship cross-shell prompt – it seems pretty nice, but I get some errors: [WARN] - (starship::utils): Executing command ...
New
Emily
I have VueJS GUIs with the project generated using Webpack. I have Elixir modules that will need to be used by the VueJS GUIs. I forese...
New
freewebwithme
Using vs code and installed ElixirLS: support and debugger. And I got an error popped up on start up says Failed to run ‘elixir’ comma...
New
dblack
I’ve got an issue with an app and I’ve no idea of how to troubleshoot it. I’m hoping someone here might have seen something similar. I p...
New
klo
Got a question about when to concat vs. prepending items to list then reversing to achieve appending. So i know lists boil down to [1 | ...
New

We're in Beta

About us Mission Statement