hauleth
defconstant - library for defining constants in your module
It is partially a response to @PragTob’s blogpost
and @michalmuskala’s tweet:
We need proper first-class constants in Erlang that a module can define
It simply allows you to quickly define constants in your modules without resolving to “ugly hacks” in form of module attributes or unquote in “weird places”.
Source:
https://github.com/hauleth/defconst
Hex:
Usage is dumb simple. There are 2 macros provided:
defconst- for compile time constantsdefonce- for runtime constants - what it means is that the value of this function will be lazily computed during first call and then cached inpersistent_termfor future uses
Example:
defmodule Foo do
import Defconstant
defconst comptime do
# This will be evaulated at compile time
Enum.sum([
0, 2, 3, 4, 5, 6, 8, 12, 30, 32, 33, 34, 35, 36, 38, 40, 42, 43, 44, 45,
46, 48, 50, 52, 53, 54, 55, 56, 58, 60, 62, 63, 64, 65, 66, 68, 80, 82,
83, 84, 85, 86, 88
])
end
defonce runtime do
2 * 1068 + 1
end
end
And that is it.
Oh, one (obvious) limitation - it can define only 0-ary functions, as otherwise it would be impossible to have “constants”. If you want to have caching based on arguments, then you need to look up for other libraries.
Most Liked
juanjoc
axelson
greven
Last Post!
greven
I guess since the docs pushed to just use module attributes, it’s normal people would just use that, I try to follow conventions over libraries unless there is a clear gap in the std. ![]()
But your library is sound!
Popular in Announcing
Other popular topics
Categories:
Sub Categories:
Forums
Popular Tags
- #ecto
- #liveview
- #troubleshooting
- #learning-elixir
- #deployment
- #library
- #erlang
- #testing
- #genserver
- #mix
- #absinthe
- #remote-other
- #otp
- #plug
- #how-to-question
- #macros
- #postgres
- #channels
- #elixirconf
- #exunit
- #discussion
- #code-sync
- #javascript
- #podcasts
- #onsite
- #dialyzer
- #docker
- #authentication
- #umbrella
- #full-time-contract
- #podcasts-by-brainlid
- #ecto-query
- #elixir-ls
- #phoenix_html
- #iex
- #blog-post
- #graphql
- #genstage
- #ai
- #websockets
- #supervisor
- #elixirconf-us
- #advent-of-code
- #distillery
- #processes
- #api
- #forms
- #metaprogramming
- #security
- #hex









