Created
September 18, 2015 14:20
-
-
Save CrowdHailer/1a9c8d76047f35fd69c9 to your computer and use it in GitHub Desktop.
Creating stateful module in elixir
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# Using the erlang mechanism of tuple modules it is possible to create a "stateful module". | |
# This concept of a stateful module is discussed in "Programming erlang" Second edition. | |
defmodule User do | |
defstruct name: nil, admin: false, internal: "kinda private" | |
def new(name, options \\ []) do | |
dependencies = struct(%__MODULE__{name: name}, options) | |
{__MODULE__, dependencies} | |
end | |
def name({__MODULE__, my}) do | |
my.name | |
end | |
def admin?({__MODULE__, my}) do | |
my.admin | |
end | |
end | |
me = User.new("Peter") | |
IO.puts me.name | |
IO.puts me.admin? | |
bob = User.new("Bob", admin: true) | |
IO.puts bob.name | |
IO.puts bob.admin? | |
bob.internal |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Ew. :/