Guest User

Untitled

a guest
Jan 16th, 2019
88
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.15 KB | None | 0 0
  1. defmodule Constants do
  2. @moduledoc """
  3. An alternative to use @constant_name value approach to defined reusable
  4. constants in elixir.
  5.  
  6. This module offers an approach to define these in a
  7. module that can be shared with other modules. They are implemented with
  8. macros so they can be used in guards and matches
  9.  
  10. ## Examples:
  11.  
  12. Create a module to define your shared constants
  13.  
  14. defmodule MyConstants do
  15. use Constants
  16.  
  17. define something, 10
  18. define another, 20
  19. end
  20.  
  21. Use the constants
  22.  
  23. defmodule MyModule do
  24. require MyConstants
  25. alias MyConstants, as: Const
  26.  
  27. def myfunc(item) when item == Const.something, do: Const.something + 5
  28. def myfunc(item) when item == Const.another, do: Const.another
  29. end
  30.  
  31. """
  32.  
  33. defmacro __using__(_opts) do
  34. quote do
  35. import Constants
  36. end
  37. end
  38.  
  39. @doc "Define a constant"
  40. defmacro constant(name, value) do
  41. quote do
  42. defmacro unquote(name), do: unquote(value)
  43. end
  44. end
  45.  
  46. @doc "Define a constant. An alias for constant"
  47. defmacro define(name, value) do
  48. quote do
  49. constant unquote(name), unquote(value)
  50. end
  51. end
  52. end
Add Comment
Please, Sign In to add comment