Skip to content

Instantly share code, notes, and snippets.

@ggpasqualino
Last active November 25, 2015 19:17
Show Gist options
  • Save ggpasqualino/52cf16c27baaa021e9f4 to your computer and use it in GitHub Desktop.
Save ggpasqualino/52cf16c27baaa021e9f4 to your computer and use it in GitHub Desktop.
Code examples for ruby meetup - Elixir edition
{:ok, agent} = Agent.start_link(fn -> [] end)
Agent.get(agent, fn list -> list end) # => []
Agent.update(agent, fn list -> ["eggs"|list] end) # => :ok
Agent.get(agent, fn list -> list end) # => ["eggs"]
Agent.stop(agent) # => :ok

In one directory

iex --sname one

In another directory

iex --sname two

In IEx one

Node.connect :"two@COMPUTER_NAME"
Node.list

In IEx two

Node.list

List the files of the working directory of the other Node

fun = fn -> IO.puts(Enum.join(File.ls!, ",")) end
Node.spawn(:"one@COMPUTER_NAME", fun)
Node.spawn(:"two@COMPUTER_NAME", fun)

For Nodes in different machines start IEx with full name and a common secret cookie

iex --name one@DOMAIN_OR_IP --cookie SECRET_COOKIE
iex --name two@DOMAIN_OR_IP --cookie SECRET_COOKIE
defmodule GenServerStack do
use GenServer
def handle_call(:pop, _from, [h|t]) do
{:reply, h, t}
end
def handle_cast({:push, item}, state) do
{:noreply, [item|state]}
end
end
{:ok, pid} = GenServer.start_link(GenServerStack, [:hello])
GenServer.call(pid, :pop) # => :hello
GenServer.cast(pid, {:push, :world}) # => :ok
GenServer.call(pid, :pop) # => :world
class Leak
attr_reader :state
def initialize
@state = {}
end
end
leak = Leak.new
leak.state[:inject] = :state
leak.state # => { :inject => :state }
defmodule Stack do
def init(state) do
new_state = state
receive do
{ client, :pop } ->
[h | new_state] = state
send client, { self(), :result, h }
{ client, :push, value } ->
new_state = [value | state]
send client, { self(), :ok }
end
init(new_state)
end
end
pid = spawn(Stack, :init, [[:hello]])
send(pid, {self(), :pop})
send(pid, {self(), :push, :world})
send(pid, {self(), :pop})
flush
fun = fn ->
IO.puts "Started long function"
:timer.sleep(2000)
IO.puts "Finished long function"
end
fun.()
Task.async(fun)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment