Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do you define constants in Elixir modules?

Tags:

elixir

In Ruby, if one were defining constants in classes, they would define them using all caps. For example:

class MyClass   MY_FAVORITE_NUMBER = 13 end 

How do you do this in Elixir? And if no such equivalent exists, how do you get around the problem of magic numbers in Elixir?

like image 923
Martimatix Avatar asked Nov 22 '15 04:11

Martimatix


People also ask

How do you declare a variable in Elixir?

Naming variables follow a snake_case convention in Elixir, i.e., all variables must start with a lowercase letter, followed by 0 or more letters(both upper and lower case), followed at the end by an optional '?' OR '!' .

What are module attributes Elixir?

Module attributes in Elixir serve three purposes: They serve to annotate the module, often with information to be used by the user or the VM . They work as constants. They work as a temporary module storage to be used during compilation.

What is __ module __ In Elixir?

__MODULE__ is a compilation environment macros which is the current module name as an atom.

What are Elixir macros?

Macros are compile-time constructs that are invoked with Elixir's AST as input and a superset of Elixir's AST as output. Let's see a simple example that shows the difference between functions and macros: defmodule Example do defmacro macro_inspect(value) do IO.


1 Answers

You can prepend your variable name with @:

defmodule MyModule do   @my_favorite_number 13 end 

Here are the docs

like image 189
AbM Avatar answered Sep 19 '22 19:09

AbM