Skip to content

Instantly share code, notes, and snippets.

@CrowdHailer
Created September 18, 2015 14:20
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CrowdHailer/1a9c8d76047f35fd69c9 to your computer and use it in GitHub Desktop.
Save CrowdHailer/1a9c8d76047f35fd69c9 to your computer and use it in GitHub Desktop.
Creating stateful module in elixir
# 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
@lpil
Copy link

lpil commented Dec 3, 2015

Ew. :/

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment