How to persist and replay an IEx session

Hello folks,
Suppose I wish to follow a book, which instructs us to key in a set of elixir expressions/functions in IEx. I’m supposed to validate and learn from the outputs/errors coming from the session. Now I’d like to save that session in a file and be able to “replay” it for future reference/refreshing or even for teaching others.

Is there a feature/scheme in IEx which enables me to achieve this? I’ve read about the .iex.exs file but it appears to me this file is not intended for the purpose I’m talking about here.

Any pointers will be greatly appreciated. Many thanks
Ramesh

Maybe something like asciinema would work?

2 Likes

@rameshkumar There are no features I know that allow saving specific part of history into session files, but there is something really similar for Erlang/OTP 20+ …

You need to set ERL_AFLAGS environment variable for example in bash:

export ERL_AFLAGS="-kernel shell_history enabled"

Make sure you add this to your shell init file (depends on shell and OS/distribution) for example in bash you need to add it to $HOME/.bashrc or ~/.bashrc (same but shorter).

Source:

Of course nothing stops you from writing code like:

defmodule MyBook.MyChapter.MyTopic do
  def my_lesson(…) do
    
  end
end

IO.puts("Book: …")

IO.puts("Chapter: …")

IO.puts("Topic: …")

IO.puts("Lesson: …")
result = MyBook.MyChapter.MyTopic.my_lesson(…)
Logger.debug(result, label: "Result:")

# other lessons …

# other topics …

# other chapters …

# other books …
3 Likes

Thanks @nickdichev. But I was looking for something a little native within IEx itself.

Thank you @Eiji. Not exactly what I had looked for but persisting the history itself is something that I’ve been yearning for.

As for your suggestion of using defmodule, def, IO.puts etc, I wanted to avoid this to enable students to not need to be aware of modules/functions to show some code examples.

Thank a lot in any case. :pray:

ok, it’s also not a big problem

For example you can write files in directories like:
examples/my_book/my_chapter/my_topic/my_lesson.ex

Then you need just put contents of such function to my_lesson.ex file and run: elixir my_lesson.ex.

echo 'DateTime.utc_now() |> to_string() |> IO.puts()' > example.ex
elixir example.ex
# output:
2019-06-02 10:15:00.000000Z

For sure I gave examples with modules and directories structure in order to well group code examples. Nobody stops you from writing code to files like examples/1.ex or examples.ex where each example is separated by code. At least for me it’s not a good practice, but in programming you are free to do everything you want - even if it’s one huge mistake. :077:

2 Likes

Generally when it is run as a script via elixir the extension is .exs though. :slight_smile:

2 Likes

I would go old school and use the Unix shell command script

3 Likes