<?xml version="1.0" encoding="UTF-8"?><rss xmlns:dc="http://purl.org/dc/elements/1.1/" xmlns:content="http://purl.org/rss/1.0/modules/content/" xmlns:atom="http://www.w3.org/2005/Atom" version="2.0" xmlns:cc="http://cyber.law.harvard.edu/rss/creativeCommonsRssModule.html">
    <channel>
        <title><![CDATA[Stories by Dennis Beatty on Medium]]></title>
        <description><![CDATA[Stories by Dennis Beatty on Medium]]></description>
        <link>https://medium.com/@dnsbty?source=rss-5e20186419e------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*inz-xlcEJASk8PxVKBKfFw.jpeg</url>
            <title>Stories by Dennis Beatty on Medium</title>
            <link>https://medium.com/@dnsbty?source=rss-5e20186419e------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 30 Nov 2026 20:34:44 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@dnsbty/feed" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[How to Create a Counter with Phoenix LiveView]]></title>
            <link>https://medium.com/@dnsbty/how-to-create-a-counter-with-phoenix-liveview-dc273bcb4d58?source=rss-5e20186419e------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc273bcb4d58</guid>
            <category><![CDATA[tutorial]]></category>
            <category><![CDATA[liveview]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[phoenix-framework]]></category>
            <dc:creator><![CDATA[Dennis Beatty]]></dc:creator>
            <pubDate>Tue, 19 Mar 2019 14:32:00 GMT</pubDate>
            <atom:updated>2019-03-19T15:25:11.796Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F2bipVjOcvdI%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D2bipVjOcvdI&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F2bipVjOcvdI%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/12c1d0857237c858286be370d3b6f8e7/href">https://medium.com/media/12c1d0857237c858286be370d3b6f8e7/href</a></iframe><p>If you follow Elixir Twitter very closely, you probably noticed that <a href="https://twitter.com/chris_mccord/status/1106291353670045696">Chris McCord released Phoenix LiveView on Friday</a>. Chris (and the other original contributors) did a great job with the release: it has thorough documentation and I was especially impressed with <a href="https://github.com/chrismccord/phoenix_live_view_example">the examples</a> that were released at the same time. I’m going to walk you through creating a counter similar to one of the examples above, but I’m going to simplify it to be as basic as possible and try to explain each step of the way. Please <a href="https://twitter.com/dnsbty">reach out to me on Twitter</a> if you have any questions about this.</p><h3>New Project</h3><p>To start out, let’s create a new Phoenix-based project called live_view_counter. We’ll use the <a href="https://hexdocs.pm/phoenix/installation.html">Phoenix generator</a>, and tell it not to include Ecto, since we won’t be using a database for this.</p><pre>mix phx.new live_view_counter --no-ecto</pre><p>Hit Y to install dependencies. Then cd into your project folder and add LiveView to the list of dependencies in the deps function of your mix.exs file:</p><pre>{:phoenix_live_view, github: &quot;phoenixframework/phoenix_live_view&quot;}</pre><p>Finally get the new dependency with mix deps.get.</p><h3>Configure</h3><p>Now we’ll want to add a signing salt. This is a security mechanism for guarding against man-in-the-middle attacks. You can use mix phx.gen.secret 32 to generate the salt for you, or just use the one I included below. Then put it into your config. Since this is just a test project, we’ll just put it straight in the config/config.exs file, but if we were doing this in a real project, we would want to put it in our secrets:</p><pre>config :live_view_counter, LiveViewCounterWeb.Endpoint,<br>  live_view: [<br>    signing_salt: &quot;7HekGYwxATz33gM/rH9q2mV+uKJq5/Hu&quot;<br>  ]</pre><p>The next bit of configuration is to tell Phoenix to use the LiveView template engine for rendering files with a .leex extension:</p><pre>config :phoenix, template_engines: [leex: Phoenix.LiveView.Engine]</pre><p>Now we want to add the LiveView flash plug to the browser pipeline in lib/live_view_counter_web/router.ex. We’re also going to add put_layout with LiveViewCounterWeb.LayoutView to wrap our live views in the default layout:</p><pre>pipeline :browser do<br>  ...<br>  plug :fetch_flash<br>  plug Phoenix.LiveView.Flash<br>  ...<br>  plug :put_layout, {LiveViewCounterWeb.LayoutView, :app}<br>end</pre><p>Then you’ll want to import some files in lib/live_counter_web.ex. This file is a large part of the “magic” behind Phoenix. It imports and aliases the functions that help you to craft controllers, views, routers, and channels. We’re going to modify it to import the LiveView functions that will be helpful to us:</p><pre>def view do<br>  quote do<br>    ...<br>    import Phoenix.LiveView, only: [live_render: 2, live_render: 3]<br>  end<br>end</pre><pre>def router do<br>  quote do<br>    ...<br>    import Phoenix.LiveView.Router<br>  end<br>end</pre><p>Next we’ll expose a websocket through which LiveView updates can be sent to the client in lib/live_view_counter_web/endpoint.ex:</p><pre>defmodule LiveViewCounterWeb.Endpoint do<br>  use Phoenix.Endpoint</pre><pre>socket &quot;/live&quot;, Phoenix.LiveView.Socket<br>  ...<br>end</pre><p>Then we’ll need to add LiveView Javascript dependencies in assets/package.json so that the client will talk to the LiveView backend:</p><pre>{<br>  ...<br>  &quot;dependencies&quot;: {<br>    &quot;phoenix&quot;: &quot;file:../deps/phoenix&quot;,<br>    &quot;phoenix_html&quot;: &quot;file:../deps/phoenix_html&quot;,<br>    &quot;phoenix_live_view&quot;: &quot;file:../deps/phoenix_live_view&quot;<br>  }<br>  ...<br>}</pre><p>Now install the new Javascript dependency with cd assets &amp;&amp; npm install. We’re almost done configuring. Enable connecting to a LiveView socket at the bottom of assets/js/app.js:</p><pre>import LiveSocket from &quot;phoenix_live_view&quot;</pre><pre>let liveSocket = new LiveSocket(&quot;/live&quot;)<br>liveSocket.connect()</pre><p>Then let’s set modify our live reload patterns in config/dev.exs so that we get live reloading of LiveView templates:</p><pre>config :live_view_counter, LiveViewCounterWeb.Endpoint,<br>  live_reload: [<br>    patterns: [<br>      ...,<br>      ~r{lib/live_view_counter_web/live/.*(ex)$}<br>    ]<br>  ]</pre><p>And last step (this one is optional so you don’t need to), we’ll import the default CSS styles in assets/css/app.css by appending:</p><pre>@import &quot;../../deps/phoenix_live_view/assets/css/live_view.css&quot;;</pre><p>And we’re all set up! To make sure everything is good you can run mix phx.server. Everything should compile and then if you go to <a href="http://localhost:4000/">http://localhost:4000</a> in your browser, you should see Replied phoenix:live_reload :ok. Once Phoenix LiveView is a little bit more stable, I imagine that it will be baked in to the Phoenix generator so that you don’t have to do all that boilerplate work every time. But now we’re on to the fun part.</p><h3>The Counter</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*SNtCjrkZ1yipMf4k.gif" /></figure><p>To create the counter, we’ll start by replacing our default route in lib/live_view_counter_web/router.ex with a new live route:</p><pre>...<br>scope &quot;/&quot;, LiveViewCounterWeb do<br>  pipe_through :browser</pre><pre>live(&quot;/&quot;, CounterLive)<br>end<br>...</pre><p>With the route set up, we’ll create a new folder in lib/live_view_counter_web called live with a counter_live.ex file inside of it. It appears that appending _live to the end of the file name will be the convention, similar to how controllers have _controller appended to the end. We’ll use Phoenix.LiveView to pull in all of the functions that we need to be able to create a LiveView view:</p><pre>defmodule LiveViewCounterWeb.CounterLive do<br>  use Phoenix.LiveView<br>end</pre><p>Now let’s add a render function to our module. This is the focal point of our new live module, as it renders the actual DOM element. We’ll render a counter that will display the current value as well as buttons for incrementing and decrementing the count:</p><pre>def render(assigns) do<br>  ~L&quot;&quot;&quot;<br>  &lt;div&gt;<br>    &lt;h1&gt;The count is: &lt;%= <a href="http://twitter.com/val">@val</a> %&gt;&lt;/h1&gt;<br>    &lt;button phx-click=&quot;dec&quot;&gt;-&lt;/button&gt;<br>    &lt;button phx-click=&quot;inc&quot;&gt;+&lt;/button&gt;<br>  &lt;/div&gt;<br>  &quot;&quot;&quot;<br>end</pre><p>You’ll notice that our multiline string starts with a sigil you’re probably unfamiliar with: ~L. This is the new syntax for defining a LiveView template. Now when you run this, you’ll see an exception raised in the terminal:</p><pre>** (ArgumentError) assign @val not available in eex template.</pre><p>This is because we used @val in our render function, but it never gets assigned. We’ll take care of this with LiveView’s mount/2 function. Add it after the render function in counter_live.ex:</p><pre>def mount(_session, socket) do<br>  {:ok, assign(socket, :val, 0)}<br>end</pre><p>You’ll notice that uses the same syntax as assigning data to a Phoenix channel. mount/2 will be invoked when the live view is rendered from the controller. It receives the session data and LiveView socket, and should generate the necessary data for initially rendering the view. render/1 will be invoked once mount/2 is complete. So basically we’re now setting @val to 0 and then rendering the view. When you refresh your browser, the app should now display properly.</p><p>So now let’s look at those buttons we created. You’ll notice they have a phx-click attribute set on them. This creates a binding that sends a click event to the LiveView server. So let’s create functions to handle those events:</p><pre>def handle_event(&quot;inc&quot;, _, socket) do<br>  {:noreply, update(socket, :val, &amp;(&amp;1 + 1))}<br>end</pre><pre>def handle_event(&quot;dec&quot;, _, socket) do<br>  {:noreply, update(socket, :val, &amp;(&amp;1 - 1))}<br>end</pre><p>Try using the + and - buttons in your browser now, and then we’ll talk about how this works. But congratulations! You have an application with LiveView up and running. 🎉</p><p>The &quot;inc&quot; and &quot;dec&quot; values come from the value provided to the phx-click attribute. The second argument (that we’re ignoring in this case) is a value, but you could potentially use that to increment by different amounts rather than just 1 by adding a phx-value attribute to the buttons.</p><p>Now that we have a working app, let’s refactor it to use a LiveEEx template. Right now we have our code just sitting in the live view. Let’s start by creating a new file at lib/live_view_counter_web/templates/counter/index.html.leex. Then we’ll copy our HTML code from the render function into the new .leex file:</p><pre>&lt;div&gt;<br>  &lt;h1 phx-click=&quot;boom&quot;&gt;The count is: &lt;%= <a href="http://twitter.com/val">@val</a> %&gt;&lt;/h1&gt;<br>  &lt;button phx-click=&quot;dec&quot;&gt;-&lt;/button&gt;<br>  &lt;button phx-click=&quot;inc&quot;&gt;+&lt;/button&gt;<br>&lt;/div&gt;</pre><p>Then we’ll need to create a new view to render that file at lib/live_view_counter_web/views/counter_view.ex. It should be pretty simple:</p><pre>defmodule LiveViewCounterWeb.CounterView do<br>  use LiveViewCounterWeb, :view<br>end</pre><p>Now let’s modify our live view to use the new view and template:</p><pre>defmodule LiveViewCounterWeb.CounterLive do<br>  use Phoenix.LiveView<br>  alias LiveViewCounterWeb.CounterView</pre><pre>def render(assigns) do<br>    CounterView.render(&quot;index.html&quot;, assigns)<br>  end<br>  ...<br>end</pre><p>So now we’re rendering out of a template and our code looks a bit cleaner! 🎉</p><h3>Next Steps</h3><p>Phoenix LiveView allows you to do some pretty cool stuff without ever having to touch frontend Javascript code. It’s still in the early stages, so you probably want to think quite a bit before using it in production. That being said, I really like the API of it. I’ll probably do a followup tutorial that tracks changes in a database. I’d recommend checking out the <a href="https://github.com/chrismccord/phoenix_live_view_example">examples repo</a> if you’re interested in seeing more of what you can do with LiveView.</p><p>Please let me know if you end up building anything cool with LiveView. I’m excited to see all the applications people dream up. Also please let me know if you have any feedback on this post or the video. You can find me on <a href="https://twitter.com/dnsbty">Twitter at dnsbty</a> or just let me know in the comments of <a href="https://youtu.be/2bipVjOcvdI">the video</a> above. I plan to continue releasing videos like this, so if you’re interested, please like the video and <a href="https://www.youtube.com/channel/UC9l_1J8y_au9Nlgrfz0rduw?sub_confirmation=1">subscribe to my channel</a> so that YouTube will let you know when they come out. Thanks for reading!</p><p><em>Originally published at </em><a href="https://dennisbeatty.com/2019/03/19/how-to-create-a-counter-with-phoenix-live-view.html"><em>dennisbeatty.com</em></a><em> on March 19, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc273bcb4d58" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cool CLIs in Elixir (Part 2) with IO.ANSI]]></title>
            <link>https://medium.com/@dnsbty/cool-clis-in-elixir-part-2-with-io-ansi-c1fbabebc52d?source=rss-5e20186419e------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1fbabebc52d</guid>
            <category><![CDATA[ansi]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[cli]]></category>
            <dc:creator><![CDATA[Dennis Beatty]]></dc:creator>
            <pubDate>Tue, 12 Mar 2019 14:34:00 GMT</pubDate>
            <atom:updated>2019-03-13T21:39:36.035Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FsN7Fy5pwOdE%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DsN7Fy5pwOdE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FsN7Fy5pwOdE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/b4833c3ff37cbc57c94ae37158c37e3f/href">https://medium.com/media/b4833c3ff37cbc57c94ae37158c37e3f/href</a></iframe><p>In the last post, I talked about <a href="https://dennisbeatty.com/2019/01/09/cool-clis-in-elixir-with-io-write-2.html">using IO.write/2 to create cool CLIs</a>. After writing that post, I got lots of great feedback along with recommendations for further topics. So that’s exactly what I’m doing. IO.write/2 is a cool function, but the real work there is done by the carriage return (\r). Carriage returns are a control character that let you reset the cursor to the beginning of the current line of text, similar to how an old-fashioned typewriter works. There are many other control characters that do a similar job. If you want to learn more about the history of how terminals and command line interfaces came about, I highly recommend this <a href="https://youtu.be/4RPtJ9UyHS0">Crash Course on Keyboards &amp; Commend Line Interfaces</a>.</p><p><a href="https://en.wikipedia.org/wiki/ANSI_escape_code">ANSI escape sequences</a> are similar to carriage returns: they’re sequences of bytes that can be output to control the terminal. Almost 50 years ago they were implemented as a standard, and allow you to move the cursor to the front of the current line similar to the carriage return. They have a lot more functionality on top of that though. ANSI escape sequences are a little more complicated to remember and type. They look something like this: \u001b[0m. Good luck remembering that one! Luckily for us, Elixir has a wonderful library built in to the language that abstracts away the need to remember the sequences: <a href="https://hexdocs.pm/elixir/IO.ANSI.html">IO.ANSI</a>.</p><h3>Colors</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*30UCCHgrEX_Ltz5-.gif" /><figcaption>All the possible IO.ANSI colors you can work with</figcaption></figure><p>One of the most common uses of IO.ANSI is to change the color of text in a terminal output. You can see that when you run mix test and the line of green dots crosses the screen, or when an exception is thrown and the error and stacktrace show up in red. Well, let’s replicate some of that functionality.</p><p>We’ll start with the green. Let’s create a module called Color that has a green function. It will accept the text to make green and return a string with the green text. To do that, we’ll just prepend IO.ANSI.green/0 to the string that we want to be green. Then outside of the module we can call our function so that when we run elixir color.ex it will run the function. Make sure that you use IO.puts/1 or IO.write/1 to output your text because just calling the function won’t display anything.</p><pre>defmodule Color do<br>  def green(text) do<br>    IO.ANSI.green() &lt;&gt; text<br>  end<br>end</pre><pre>IO.puts Color.green(&quot;This text is green&quot;)</pre><p>Now save the file and run it in your terminal with elixir color.ex (assuming you named your file color.ex) and you’ll notice that after you run the program, the next line in your terminal continues to be green. That’s because the terminal will stick with that color until it’s told otherwise. To combat that, we’ll need to use IO.ANSI.reset/0 in our green/1 function:</p><pre>def green(text) do<br>  IO.ANSI.green() &lt;&gt; text &lt;&gt; IO.ANSI.reset()<br>end</pre><p>Now things should work as planned! So we can copy this same pattern for red text:</p><pre>defmodule Color do<br>  ...<br>  def red(text) do<br>    IO.ANSI.red() &lt;&gt; text &lt;&gt; IO.ANSI.reset()<br>  end<br>end<br>...<br>IO.puts Color.red(&quot;This text is red&quot;)</pre><p>The most basic terminals support 8 different colors:</p><ul><li>black</li><li>red</li><li>green</li><li>yellow</li><li>blue</li><li>magenta</li><li>cyan</li><li>white</li></ul><p>You can use this method for any of the eight. You can also try out modifiers like IO.ANSI.light_red/0 or IO.ANSI.red_background/0 or IO.ANSI.light_red_background/0. I highly recommend checking out <a href="https://github.com/elixir-lang/elixir/blob/v1.8.1/lib/elixir/lib/io/ansi.ex#L133-L147">the metaprogramming that implements these in the IO.ANSI source code</a>. It’s an interesting bit of code.</p><p>More advanced terminals support up to 256 colors. That would be a lot of colors to have a function for each one, so this is implemented with IO.ANSI.code/1. It allows us to specify a code between 0 and 255 to select a color. Let’s check out all the possibilities:</p><pre>defmodule Color do<br>  ...<br>  def code(code, text) do<br>    IO.ANSI.color(code) &lt;&gt; text &lt;&gt; IO.ANSI.reset()<br>  end<br>end<br>...<br>Enum.each(0..255, fn code -&gt;<br>  IO.puts Color.code(code, &quot;Code #{code}&quot;)<br>  Process.sleep(10)<br>end)</pre><p>All of those colors can also be used with IO.ANSI.color_background/1 to set the background color. You can even set a background and foreground for the same text. If you don’t want have to write that code every time to see the color codes, you can use <a href="https://upload.wikimedia.org/wikipedia/commons/1/15/Xterm_256color_chart.svg">this graphic</a>.</p><h3>Docker Compose</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*ubR4TAKsOUNKS19J.gif" /><figcaption>A docker-compose clone written in Elixir</figcaption></figure><p>Docker Compose is a tool that allows you to control several Docker containers from one place. I noticed that when you run docker-compose up with multiple Docker containers defined, those containers will be started up in parallel, not necessarily finishing in the order they started. In the command line, you will see that it says that it’s starting all of the images, and then one by one will print done next to the ones that finished.</p><p>Notice these aren’t on the same line, so somehow Docker is printing over previous lines. That’s more than a simple carriage return, but luckily IO.ANSI is up to the task. Let’s start out by creating a Docker module with an up function that will “start” three different apps.</p><pre>defmodule Docker do<br>  def up do<br>    IO.puts &quot;Creating network \&quot;dgraph_default\&quot; with the default driver&quot;<br>    IO.puts &quot;Creating dgraph_zero_1   ... &quot;<br>    IO.puts &quot;Creating dgraph_server_1 ... &quot;<br>    IO.puts &quot;Creating dgraph_ratel_1  ... &quot;<br>  end<br>end</pre><pre>Docker.up()</pre><p>Now we need to display when each app is done “spinning up”. And to make it obvious that we’re updating these after the fact, we’ll sleep the process and update them in a different order. To do this, we’ll first want to set up a module attribute to contain the green “done” text:</p><pre>defmodule Docker do<br>  <a href="http://twitter.com/done_text">@done_text</a> IO.ANSI.green() &lt;&gt; &quot;done&quot; &lt;&gt; IO.ANSI.reset()<br>  ...</pre><p>Then we can create a line_done/1 function that will take in the line number that completed and append the “done” text to the end of it. We’ll start by sleeping for a half second so we can see the work being done. Then we’ll move the cursor to the end of the line we want to modify and write the text. Finally we’ll need to move the cursor back to the starting position so we know where it is and then write the whole thing to the console:</p><pre>defmodule Docker do<br>  ...<br>  defp line_done(line) do<br>    Process.sleep(500)<br>    offset = 4 - line</pre><pre>offset<br>    |&gt; IO.ANSI.cursor_up() # move the cursor up to the line we want to modify<br>    |&gt; Kernel.&lt;&gt;(IO.ANSI.cursor_right(30)) # move the cursor to the end of the line (30 chars)<br>    |&gt; Kernel.&lt;&gt;(<a href="http://twitter.com/done_text">@done_text</a>) # write the done text<br>    |&gt; Kernel.&lt;&gt;(&quot;\r&quot;) # move the cursor to the front of the line<br>    |&gt; Kernel.&lt;&gt;(IO.ANSI.cursor_down(offset)) # move the cursor back to the bottom<br>    |&gt; IO.write()<br>  end<br>end<br>...</pre><p>So now your whole file should look something like this:</p><pre>defmodule Docker do<br>  <a href="http://twitter.com/done_text">@done_text</a> IO.ANSI.green() &lt;&gt; &quot;done&quot; &lt;&gt; IO.ANSI.reset()</pre><pre>def up do<br>    IO.puts &quot;Creating network \&quot;dgraph_default\&quot; with the default driver&quot;<br>    IO.puts &quot;Creating dgraph_zero_1   ... &quot;<br>    IO.puts &quot;Creating dgraph_server_1 ... &quot;<br>    IO.puts &quot;Creating dgraph_ratel_1  ... &quot;</pre><pre>1..3<br>    |&gt; Enum.shuffle()<br>    |&gt; Enum.each(&amp;line_done/1)<br>  end</pre><pre>defp line_done(line) do<br>    Process.sleep(500)<br>    offset = 4 - line</pre><pre>offset<br>    |&gt; IO.ANSI.cursor_up() # move the cursor up to the line we want to modify<br>    |&gt; Kernel.&lt;&gt;(IO.ANSI.cursor_right(30)) # move the cursor to the end of the line (30 chars)<br>    |&gt; Kernel.&lt;&gt;(<a href="http://twitter.com/done_text">@done_text</a>) # write the done text<br>    |&gt; Kernel.&lt;&gt;(&quot;\r&quot;) # move the cursor to the front of the line<br>    |&gt; Kernel.&lt;&gt;(IO.ANSI.cursor_down(offset)) # move the cursor back to the bottom<br>    |&gt; IO.write()<br>  end<br>end</pre><pre>Docker.up()</pre><p>If you want a followup exercise, randomize the finish state of each app so that it can either be a green “done” or a red “error”. You could also make the app list dynamic so that even with 12 lines you’re writing the status on the proper line.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*_42Wc9SM5p1tuRDE.gif" /><figcaption>A downloader UI that covers the Terminal screen written in Elixir</figcaption></figure><p>The final example this post will cover is covering the terminal (see what I did there?). IO.ANSI has a nifty function called cover/0 that will let you cover the entire terminal window in the current background color. So we’re going to use that to make a nifty “downloader” UI. Let’s start by creating a screen for specifying a save filename. We’ll create a module called Downloader and give it a function called get_filename/0 that will allow us to capture the filename. We’ll start with just covering the screen in our specified background color:</p><pre>defmodule Downloader do<br>  <a href="http://twitter.com/background_color">@background_color</a> 53</pre><pre>def get_filename do<br>    draw_background()<br>  end</pre><pre>defp draw_background do<br>    IO.write IO.ANSI.color_background(<a href="http://twitter.com/background_color">@background_color</a>) &lt;&gt; IO.ANSI.clear()<br>  end<br>end</pre><pre>Downloader.get_filename()</pre><p>Now if you run that you’ll see that once the program ends your terminal is still covered in the purple background color (unless you chose a different number instead of 53). So to take care of that, let’s add a new function called reset/0 that will reset the ANSI settings and then clear the screen at the end of getting the filename:</p><pre>  ...<br>  def get_filename do<br>    ...<br>    reset()<br>  end<br>  ...<br>  def reset do<br>    IO.write IO.ANSI.reset() &lt;&gt; IO.ANSI.clear()<br>  end<br>  ...</pre><p>If you try running it now you probably won’t actually see anything in your terminal because we’re clearing it right after painting on it. Well let’s change that by printing our label and input and then using IO.read/1 to wait for the user to enter a filename:</p><pre>defmodule Downloader do<br>  ...<br>  <a href="http://twitter.com/label_color">@label_color</a> 15<br>  <a href="http://twitter.com/input_color">@input_color</a> 183<br>  <a href="http://twitter.com/input_text_color">@input_text_color</a> 53<br>  <a href="http://twitter.com/input_size">@input_size</a> 20<br>  <a href="http://twitter.com/label_text">@label_text</a> &quot;Filename&quot;</pre><pre>def get_filename do<br>    draw_background()<br>    draw_input()</pre><pre>filename = IO.read(:line) # read the entire line when the user presses Enter</pre><pre>reset()</pre><pre>filename<br>  end</pre><pre>defp draw_input do<br>    IO.puts IO.ANSI.color(<a href="http://twitter.com/label_color">@label_color</a>) &lt;&gt; <a href="http://twitter.com/label_text">@label_text</a><br>    IO.write IO.ANSI.color_background(<a href="http://twitter.com/input_color">@input_color</a>) &lt;&gt; input_box()<br>    IO.write &quot;\r&quot; &lt;&gt; IO.ANSI.color(<a href="http://twitter.com/input_text_color">@input_text_color</a>)<br>  end</pre><pre>defp input_box do<br>    String.duplicate(&quot; &quot;, <a href="http://twitter.com/input_size">@input_size</a>)<br>  end<br>  ...<br>end</pre><pre>Downloader.get_filename()<br>|&gt; IO.inspect(label: &quot;Filename&quot;)</pre><p>Now when you run this, you should see a purple screen with an input that says “Filename” above it. When you type something in and press enter you should get a line that looks like Filename: &quot;name.ex\n&quot;. We don’t really want that newline there, so let’s go ahead and change the returning line of our get_filename/0 function to remove it. Elixir has a handy function built in to the String library that we can use. <a href="https://hexdocs.pm/elixir/String.html#trim/1">String.trim/1</a> will remove any whitespace from the beginning or end of a string:</p><pre>  ...<br>  def get_filename do<br>    ...<br>    String.trim(filename)<br>  end<br>  ...</pre><p>Now you may have noticed that the input is currently in the top left of the screen. Wouldn’t it be cooler if that were centered on the screen? Well, with IO.ANSI it’s simple to position our cursor and write somewhere else on the screen. The problem though, is that it isn’t easy to get the size of the terminal window. Erlang’s io library exposes io:rows/0 and io:columns/0 that are supposed to help with this. If you run in iex you should see something like this:</p><pre>iex&gt; :io.rows()<br>{:ok, 24}</pre><pre>iex&gt; :io.columns()<br>{:ok, 101}</pre><p>Because of that I created the following program to try using this in our program:</p><pre>defmodule Size do<br>  def get do<br>    {:ok, rows} = :io.rows()<br>    {:ok, cols} = :io.columns()<br>    {rows, cols}<br>  end<br>end</pre><pre>IO.inspect Size.get()</pre><p>When running this program I just get a MatchError because both functions return {:error, :enotsup}. According to the Erlang docs:</p><blockquote><em>The function succeeds for terminal devices and returns {error, enotsup} for all other I/O devices.</em></blockquote><p>It appears that in iex we’re exposing a terminal device, but by running elixir filename.ex we aren’t. After spending a lot of time trying to find a workaround, I decided to let tput do the work. tput is a standard Unix operating system command and so if you run tput cols in your terminal, it will display the number of columns in the window and tput lines will output the number of rows. And Elixir has a simple way to call out to another program: System.cmd/2. It takes a command and list of arguments and returns the exit status code and output.</p><p>If you know of any better way to get the terminal size in a program like this, please <a href="https://twitter.com/dnsbty">reach out and let me know</a> and I’ll happily update this post. Otherwise, let’s use System.cmd/2 and tput at the bottom of our Downloader to get our window size:</p><pre>  ...<br>  defp screen_size do<br>    {num(&quot;lines&quot;), num(&quot;cols&quot;)}<br>  end</pre><pre>  defp num(subcommand) do<br>    case System.cmd(&quot;tput&quot;, [subcommand]) do<br>      {text, 0} -&gt;<br>        text<br>        |&gt; String.trim()<br>        |&gt; String.to_integer()<br>      _ -&gt; 0<br>    end<br>  end<br>  ...</pre><p>Now let’s go ahead and take advantage of that info in our draw_input\0 function. We’ll get the total number of lines and divide by 2 to move our cursor halfway down the screen. Then we’ll subtract the input size from the total number of columns and divide that by 2 to move our cursor so that our label will be centered on the screen both vertically and horizontally and our input will be just below it:</p><pre>  ...<br>  defp draw_input do<br>    {rows, cols} = screen_size()</pre><pre>    # floor to get the line just above center when rows or cols is odd<br>    # truncate to convert float to integer<br>    row = Float.floor(rows / 2) |&gt; trunc()<br>    column = Float.floor((cols - <a href="http://twitter.com/input_size">@input_size</a>) / 2) |&gt; trunc()</pre><pre>    # move the cursor to that position and draw the label<br>    IO.write IO.ANSI.cursor(row, column) &lt;&gt; IO.ANSI.color(<a href="http://twitter.com/label_color">@label_color</a>) &lt;&gt; <a href="http://twitter.com/label_text">@label_text</a></pre><pre>    # move the cursor down a line and draw the input<br>    IO.write IO.ANSI.cursor(row + 1, column) &lt;&gt; IO.ANSI.color_background(<a href="http://twitter.com/input_color">@input_color</a>) &lt;&gt; input_box()</pre><pre>    # move the cursor to the beginning of the input<br>    IO.write IO.ANSI.cursor(row + 1, column) &lt;&gt; IO.ANSI.color(<a href="http://twitter.com/input_text_color">@input_text_color</a>)<br>  end<br>  ...</pre><p>Now if you run the program your terminal should be all purple with an input in the middle of the screen! 🎉 There’s just one remaining problem: when you run you may notice that the filename line is printing about halfway down the screen. That’s because we put the cursor in the middle of the screen to draw the input and didn’t do anything to move it back. IO.ANSI comes in clutch with a home/0 function that does just that. Let’s go ahead and append it to the end of our reset/0 function:</p><pre>  ...<br>  def reset do<br>    IO.write IO.ANSI.reset() &lt;&gt; IO.ANSI.clear() &lt;&gt; IO.ANSI.home()<br>  end<br>  ...</pre><p>And voilà! We now have a module that covers the screen to display an input and reads the input out of it. Your code should look something like this:</p><pre>defmodule Downloader do<br>  <a href="http://twitter.com/background_color">@background_color</a> 53<br>  <a href="http://twitter.com/label_color">@label_color</a> 15<br>  <a href="http://twitter.com/input_color">@input_color</a> 183<br>  <a href="http://twitter.com/input_text_color">@input_text_color</a> 53<br>  <a href="http://twitter.com/input_size">@input_size</a> 20<br>  <a href="http://twitter.com/label_text">@label_text</a> &quot;Filename&quot;</pre><pre>  def get_filename do<br>    draw_background()<br>    draw_input()</pre><pre>    filename = IO.read(:line) # read the entire line when the user presses Enter</pre><pre>    reset()</pre><pre>    String.trim(filename)<br>  end</pre><pre>  defp draw_input do<br>    {rows, cols} = screen_size()</pre><pre>    # floor to get the line just above center when rows or cols is odd<br>    # truncate to convert float to integer<br>    row = Float.floor(rows / 2) |&gt; trunc()<br>    column = Float.floor((cols - <a href="http://twitter.com/input_size">@input_size</a>) / 2) |&gt; trunc()</pre><pre>    # move the cursor to that position and draw the label<br>    IO.write IO.ANSI.cursor(row, column) &lt;&gt; IO.ANSI.color(<a href="http://twitter.com/label_color">@label_color</a>) &lt;&gt; <a href="http://twitter.com/label_text">@label_text</a></pre><pre>    # move the cursor down a line and draw the input<br>    IO.write IO.ANSI.cursor(row + 1, column) &lt;&gt; IO.ANSI.color_background(<a href="http://twitter.com/input_color">@input_color</a>) &lt;&gt; input_box()</pre><pre>    # move the cursor to the beginning of the input<br>    IO.write IO.ANSI.cursor(row + 1, column) &lt;&gt; IO.ANSI.color(<a href="http://twitter.com/input_text_color">@input_text_color</a>)<br>  end</pre><pre>  defp input_box do<br>    String.duplicate(&quot; &quot;, <a href="http://twitter.com/input_size">@input_size</a>)<br>  end</pre><pre>  defp draw_background do<br>    IO.write IO.ANSI.color_background(<a href="http://twitter.com/background_color">@background_color</a>) &lt;&gt; IO.ANSI.clear()<br>  end</pre><pre>  def reset do<br>    IO.write IO.ANSI.reset() &lt;&gt; IO.ANSI.clear() &lt;&gt; IO.ANSI.home()<br>  end</pre><pre>  defp screen_size do<br>    {num(&quot;lines&quot;), num(&quot;cols&quot;)}<br>  end</pre><pre>  defp num(subcommand) do<br>    case System.cmd(&quot;tput&quot;, [subcommand]) do<br>      {text, 0} -&gt;<br>        text<br>        |&gt; String.trim()<br>        |&gt; String.to_integer()<br>      _ -&gt; 0<br>    end<br>  end<br>end</pre><pre>Downloader.get_filename()<br>|&gt; IO.inspect(label: &quot;Filename&quot;)</pre><p>If you want to keep going with this, try pulling in what we did with the <a href="https://0.0.7.227/01/09/cool-clis-in-elixir-with-io-write-2.html#great-progress">progress bar in the last post</a>. Center it on the screen and maybe add some color to it as well. If you do, please <a href="https://twitter.com/dnsbty">reach out and show me what you come up with</a>.</p><h3>Curses</h3><p>That’s everything I intend to cover in this post. Overall ANSI escape codes allow you to do some really cool stuff with terminal output, and IO.ANSI is incredibly helpful in allowing you to work with them. There are some drawbacks however: Scroll up after running the code in our last example, and you will notice that all the times we “cover” the screen we’re really just printing enough lines that all we see is the new background color. It never really goes away. We could hack that together using IO.write to write over each line with blank characters, but there’s a better solution: <a href="https://www.gnu.org/software/ncurses/ncurses.html">ncurses</a> and specifically <a href="https://github.com/jfreeze/ex_ncurses">the ex_ncurses library</a>. It allows you to build some really powerful command line applications, and even games.</p><p>I may write about it in a later post, but in the meantime check out these awesome examples:</p><p>Like last time, please let me know if you end up using this somewhere. Also please let me know if you have any feedback on the format of this post or the video. I especially want to know if there was somewhere in the examples that you got lost so that I can work on clarifying more in the future. You can find me on <a href="https://twitter.com/dnsbty">Twitter at dnsbty</a> or on the <a href="https://elixir-slackin.herokuapp.com/">Elixir Slack group</a> with the same name. Or you can just let me know in the comments of <a href="https://youtu.be/sN7Fy5pwOdE">the video</a> above. I plan to continue releasing videos like this, so if you’re interested, please like the video and <a href="https://www.youtube.com/channel/UC9l_1J8y_au9Nlgrfz0rduw?sub_confirmation=1">subscribe to my channel</a> so that YouTube will let you know when they come out. You can also subscribe to my mailing list below or my <a href="https://t.me/dennisbeatty">Telegram channel</a> for updates. Thanks for reading!</p><p><em>Originally published at </em><a href="https://dennisbeatty.com/2019/03/12/cool-clis-in-elixir-part-2-with-io-ansi.html"><em>dennisbeatty.com</em></a><em> on March 12, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1fbabebc52d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cool CLIs in Elixir with IO.write/2]]></title>
            <link>https://medium.com/@dnsbty/cool-clis-in-elixir-with-io-write-2-577088a60ec4?source=rss-5e20186419e------2</link>
            <guid isPermaLink="false">https://medium.com/p/577088a60ec4</guid>
            <category><![CDATA[podium]]></category>
            <category><![CDATA[terminal]]></category>
            <category><![CDATA[cli]]></category>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[print]]></category>
            <dc:creator><![CDATA[Dennis Beatty]]></dc:creator>
            <pubDate>Wed, 09 Jan 2019 15:42:38 GMT</pubDate>
            <atom:updated>2019-01-16T17:56:34.402Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F_NXZJx1snkE%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D_NXZJx1snkE&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F_NXZJx1snkE%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/9e6ff5f461d516ee2a9dd35d0f68e4d7/href">https://medium.com/media/9e6ff5f461d516ee2a9dd35d0f68e4d7/href</a></iframe><p>A couple months ago I wrote a script that needed to take a CSV file with ~500k lines and process records from each of those lines. I wanted some way to keep track of the progress, and logging out each line number on a separate line was filling my console really fast. Even just outputting a single period without a newline was overwhelming. This led to me researching how to overwrite a console line. I decided to make a quick video about how to do it and try to share my knowledge.</p><h3>The IO Module</h3><p>If you’ve been working with Elixir for very long, you’ve probably seen IO.inspect/2. You can add it to your pipelines to be able to easily debug output at various stages of processing. IO.inspect/2 is built on top of IO.puts/1 which you may also be familiar with. Basically IO.puts/1 prints whatever you tell it to in the console on a new line. This can be pretty useful for debugging output as well.</p><p>What I’m excited to show you today is IO.write/1. I’ve been working primarily in Elixir for two years now, but somehow I had still never used IO.write/1 until pretty recently. IO.write/1 gives you the ability to print onto the same line as your last output, rather than putting it on a new line. This allows for some pretty cool tricks.</p><h3>Tracking Time</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*72-7I1IwFnJnkTWF.gif" /><figcaption>Clock written in Elixir being run</figcaption></figure><p>To start with, let’s create a simple clock that will run in your terminal. You can see the full code below, but we’ll create a Clock module and create a function inside of it simply called start. This function will call Time.utc_now() to get the current UTC time. Then we’ll tell it that we only care about seconds, so we’ll use Time.truncate/2 to discard any millisecond and microsecond data. Finally we’ll convert the time struct to a string.</p><pre>defmodule Clock do<br>  def start do<br>    Time.utc_now()<br>    |&gt; Time.truncate(:second)<br>    |&gt; Time.to_string()<br>  end<br>end</pre><p>Now here’s where IO.write/1 comes in. We’ll write the string out to the terminal. Then we’ll use Process.sleep/1 to tell the process to sleep for 1 second until it’s ready to display the next time. Then we’ll recursively call this same function so that it will create the loop that checks the clock every second. Finally we’ll run our Clock.start/0 function outside of the module. And now let’s run this in our terminal.</p><pre>defmodule Clock do<br>  def start do<br>    ...<br>    IO.write(time_string)<br>    Process.sleep(1_000)<br>    start()<br>  end<br>end</pre><pre>Clock.start()</pre><p>You’ll notice that now it’s printing the current time on the same line as the previous one, but we really want it to replace the current time instead. This is where special characters come in. You’ve likely seen the character for a newline (/n). Maybe you’ve seen the tab character as well (/t). I’m guessing it’s likely though that you haven’t seen the character for a carriage return. /r is a carriage return, and it returns the cursor to the beginning of the current line. When you use it you can replace text on the current line. So we’ll add that and then our final code looks like:</p><pre>defmodule Clock do<br>  def start do<br>    time_string =<br>      Time.utc_now()<br>      |&gt; Time.truncate(:second)<br>      |&gt; Time.to_string()</pre><pre>    IO.write(&quot;\r#{time_string}&quot;)<br>    Process.sleep(1_000)<br>    start()<br>  end<br>end</pre><h3>Counting Down to the End</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*wjoXbs4WGok2wYyx.gif" /><figcaption>Countdown written in Elixir being run</figcaption></figure><p>So now let’s try a different application. We’ll make a countdown: it will start at 10 and work it’s way down to 0. When it reaches 0, we’ll print out that it’s done. So for this, let’s make a module called Count with a function called count that takes in the current number. Let’s make that function write the current number to the terminal line, using our carriage return character to overwrite what was already there. Then we’ll recursively call it again with the decremented count. To slow things down and make it more obvious what’s going on, I’m going to use the Process.sleep/1 function again. Now we need to handle the base case as well and tell the program to stop when it hits 0, so let’s use pattern matching to stop when the count is at 0. And finally let’s run that function when this file gets run. Your code will look something like this:</p><pre>defmodule Count do<br>  def count(0) do<br>    IO.puts(&quot;\nDone!&quot;)<br>  end</pre><pre>  def count(current) do<br>    IO.write(&quot;\r#{current}&quot;)<br>    Process.sleep(250)<br>    count(current - 1)<br>  end<br>end</pre><pre>Count.count(10)</pre><p>Now if you try running that, you’ll notice something strange. The 0 from the 10 never goes away. That’s because when we use the carriage return, we’re telling it to overwrite what’s already there, but only as far as we actually write over it. If we don’t supply a character to replace the one that’s already there, it will leave it. So we’re going to need to add some blank spaces to overwrite the end characters. Since this is simply a countdown from 10 we can just add a single space to the end, but if it were to allow users to input whatever value they wanted, we would need to programmatically infer how many spaces to add. So if we run that again with the code below, it does what we expect.</p><pre>defmodule Count do<br>  def count(0) do<br>    IO.puts(&quot;\nDone!&quot;)<br>  end</pre><pre>  def count(current) do<br>    IO.write(&quot;\r#{current} &quot;)<br>    Process.sleep(250)<br>    count(current - 1)<br>  end<br>end</pre><pre>Count.count(10)</pre><h3>Great Progress</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*aSR4KLmkjxtuL1dR.gif" /><figcaption>Cool progress bar written in Elixir</figcaption></figure><p>That’s most of what I wanted to show you, but I want to end by showing you one of the coolest applications for this. This example is a little bit more difficult to follow, but it will allow you to add a simple progress bar to a CLI tool. My friend <a href="http://trevor-fenn.com/">Trevor Fenn</a> implemented it in Ruby for some stuff we’re doing at <a href="https://podium.com/">Podium</a>, so I’ve ported it over to Elixir for this example.</p><p>To start off we’re going to make a module called Progress containing a function called bar. Let’s have bar receive two parameters: count and total. I’m going to add a private percent_complete function that takes in the same count and total and we’ll calculate the actual percentage here. So let’s start by dividing the count by the total which gives us the decimal percentage, and then we’ll multiply that by 100 to give us a more human readable percentage. Then finally let’s round it to the nearest hundredth so that it doesn’t get too big. I’m going to use a module attribute constant for the rounding precision though so that it’s easily changeable if we want to do that later.</p><pre>defmodule Progress do<br>  @rounding_precision 2</pre><pre>  def bar(count, total) do<br>  end</pre><pre>  defp percent_complete(count, total) do<br>    Float.round(100.0 * count / total, @rounding_precision)<br>  end<br>end</pre><p>OK now that we have the percentage complete, we need to actually create the progress bar from that. So how this progress bar will work is we’re going to have two different unicode characters that we’re using. The first is a halftone box (░) and the other is a filled box (█). We’ll want to show the filled box the number of times that it takes to show the current progress and then the halftone box for the rest of it. So I’m going to create another module attribute constant called @progress_bar_size to say how many characters long the progress bar should be. I think I’m going to say 50 for now to simplify the math.</p><p>So to figure out how many percentage point each character is worth I will divide 100 by the progress bar size, so in this case, each character is worth 2% of the total. Then we’ll calculate how many completed characters we should write to the line and then subtract that from the total progress bar size to know how many incomplete characters to write.</p><pre>def bar(count, total) do<br>  percent = percent_complete(count, total)<br>  divisor = 100 / @progress_bar_size<br>  complete_count = round(percent / divisor)<br>  incomplete_count = @progress_bar_size - complete_count<br>end</pre><p>In the video, I created a new function called repeat that returns a string with the specified number of that character. When I showed my code to Trevor though, he showed me that there is a String.duplicate/2 that will do exactly what I was going for, so we’ll use that to generate the full progress bar. We’ll start by writing the repeated completed characters and then we’ll append the incomplete characters onto that. And finally let’s write the percent complete at the end to make it a little more usable.</p><pre>defmodule Progress do<br>  ...<br>  @complete_character &quot;█&quot;<br>  @incomplete_character &quot;░&quot;</pre><pre>  def bar(count, total) do<br>    ...<br>    complete = String.duplicate(@complete_character, complete_count)<br>    incomplete = String.duplicate(@incomplete_character, incomplete_count)</pre><pre>    &quot;#{complete}#{incomplete} (#{percent}%)&quot;<br>  end<br>end</pre><p>So now let’s actually run it. Outside of the module let’s say we have a total of 50 tasks to complete. So we’ll call Enum.each over a range from 1 to 50 and with each number we can generate a progress bar with the current task number and the total. Let’s go ahead and write this to the console with a carriage return at the front to tell it to overwrite the previous progress bar. Then to make it a little more visible, let’s add a Process.sleep/1 to each iteration. And then at the end let’s write a newline so that when the execution finishes it moves our cursor down to the next line.</p><pre>defmodule Progress do<br>  ...<br>end</pre><pre>total = 50<br>Enum.each(1..total, fn task -&gt;<br>  IO.write(&quot;\r#{Progress.bar(task, total)}&quot;)<br>  Process.sleep(50)<br>end)</pre><pre>IO.write(&quot;\n&quot;)</pre><p>So overall, you’re looking at something like this.</p><pre>defmodule Progress do<br>  @rounding_precision 2<br>  @progress_bar_size 50<br>  @complete_character &quot;█&quot;<br>  @incomplete_character &quot;░&quot;</pre><pre>  def bar(count, total) do<br>    percent = percent_complete(count, total)<br>    divisor = 100 / @progress_bar_size</pre><pre>    complete_count = round(percent / divisor)<br>    incomplete_count = @progress_bar_size - complete_count</pre><pre>    complete = String.duplicate(@complete_character, complete_count)<br>    incomplete = String.duplicate(@incomplete_character, incomplete_count)</pre><pre>    &quot;#{complete}#{incomplete} (#{percent}%)&quot;<br>  end</pre><pre>  defp percent_complete(count, total) do<br>    Float.round(100.0 * count / total, @rounding_precision)<br>  end<br>end</pre><pre>total = 50<br>Enum.each(1..total, fn task -&gt;<br>  IO.write(&quot;\r#{Progress.bar(task, total)}&quot;)<br>  Process.sleep(50)<br>end)<br>IO.write(&quot;\n&quot;)</pre><p>So there you have it: a pretty simple, but pretty cool progress bar for CLI applications. If you end up using this somewhere please let me know. You can find me on <a href="https://twitter.com/dnsbty">Twitter at dnsbty</a> or on the <a href="https://elixir-slackin.herokuapp.com/">Elixir Slack group</a> with the same name. Or you can just let me know in the comments of <a href="https://youtu.be/_NXZJx1snkE">the video</a> above. I’m hoping to put out more videos like this, so if you’re interested, please like the video and <a href="https://www.youtube.com/channel/UC9l_1J8y_au9Nlgrfz0rduw?sub_confirmation=1">subscribe to my channel</a> so that YouTube will let you know when they come out. Thanks for reading!</p><p><em>Originally published at </em><a href="https://dennisbeatty.com/2019/01/09/cool-clis-in-elixir-with-io-write-2.html"><em>dennisbeatty.com</em></a><em> on January 9, 2019.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=577088a60ec4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What I Learned From AirPair Founder Jonathon Kresner While in San Francisco]]></title>
            <link>https://medium.com/beehive-startups/what-i-learned-from-airpair-founder-jonathon-kresner-while-in-san-francisco-9f7cef9d486b?source=rss-5e20186419e------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f7cef9d486b</guid>
            <category><![CDATA[startup]]></category>
            <category><![CDATA[community-voice]]></category>
            <category><![CDATA[entrepreneurship]]></category>
            <dc:creator><![CDATA[Dennis Beatty]]></dc:creator>
            <pubDate>Thu, 30 Jun 2016 22:53:57 GMT</pubDate>
            <atom:updated>2016-07-25T02:30:45.869Z</atom:updated>
            <content:encoded><![CDATA[<h4><em>The journey of a thousand miles continues with one more step.</em></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*8ntjRF0AFduX0tic_7cmBA.jpeg" /></figure><p>While I was in San Francisco last month, I had the opportunity to meet up with <a href="https://twitter.com/hackerpreneur">Jonathon Kresner</a>, founder and CEO of <a href="https://twitter.com/hackerpreneur">AirPair</a>. Though we had never met, he readily invited me to drop by his apartment where we talked on his rooftop overlooking the city.</p><p>Kresner built AirPair around his vision of using technology to connect people. The platform pairs up developers with experts who can help them to learn new technologies and troubleshoot problems they may have. Kresner came up with the idea behind AirPair on Christmas Day 2012, and then built an MVP and acquired the first customer before quitting his full-time job that March. In October, <a href="https://twitter.com/ilebovic">Igor Lebovic</a>, an SEO expert and then Senior VP of Growth at About.com, joined the AirPair team, and the pair was accepted into Y Combinator’s Winter 2014 batch.</p><p>They recently finished the YC program, where they saw 40% growth each month and built an amazing network of experts in various technologies and softwares by engaging them in a way that competitors couldn’t.</p><p>Other companies in AirPair’s space have recruited great experts as well, but haven’t been able to provide customers for them. Rather than follow their lead by recruiting experts first, Kresner and Lebovic focused on finding customers, and then searched for specialized experts who could help with their specific problems on a case-by-case basis. By approaching the problem in this order, they’ve been able to ensure that experts joining the community are guaranteed a payout, rather than convincing them to join a stale platform that won’t accomplish anything for them. Kresner demonstrated his commitment to both customers and experts when he showed me AirPair’s process.</p><p>“On our system everything is hand-managed,” said Kresner. “You get an account manager who reads through your brief and decides on three people who would do a great job. So in the best case, three people are going to apply, and one person gets paid every time, so you get a one-in-three chance if we email you that it will be worth your time monetarily to interact with our system. Whereas on this other platform you have a one-in-12 chance.”</p><p>Kresner believes this advantage has benefitted AirPair since the company’s creation.</p><p>The system started as nothing but a business card. Kresner would explain the idea to people at meetups, and they would tell him things like, “I wish we’d had that last month when we made the switch from Coldfusion to Javascript.” When someone told him they were having problems with different programming languages, Kresner asked, “If I can help you solve that for $30, would you give it a shot?” This first client sent a brief via email and Kresner figured out the underlying problems and emailed the top 10 helpers for those technologies on StackOverflow. Four of the 10 replied to confirm their interest, and one was connected to the client through a Google Hangout. The client paid Kresner over Paypal and Kresner transferred the money on to the expert after taking a small cut. Only after the idea had proved itself was any code written.</p><p>“I was pretty scared to start a new company because I know what that involves after doing it a few times,” said Kresner. “It’s basically signing your life away for at least three years, so I really needed a lot of validation this time around.”</p><p>Kresner wanted to ensure that AirPair would not only attract users, but also generate revenue.</p><p>AirPair is Kresner’s second company that has grown a large userbase. The first, <a href="http://www.climbfind.com/">ClimbFind</a>, is a community connecting indoor climbers with climbing buddies. Though it grew to over 1 million users, Kresner had to leave the company because there was no cashflow. His mantra in 2013 was one he took from his father: “Happiness is a positive cashflow.” Though he was able to learn a ton and meet several friends while working with ClimbFind, Kresner is confident that leaving to start AirPair was a great move.</p><p>“With AirPair there’s a big drive to be commercial and the combination of the two works out really amazing for everyone, but it’s always a challenge balancing. AirPair is like ClimbFind done commercially, but with developers instead of climbers,” said Kresner.</p><p>Though ClimbFind never found financial success in the way AirPair has, four couples were married after meeting through the platform. This has really fueled Kresner’s passion for using technology to connect people.</p><p>“Changing people’s lives is the most rewarding thing for me,” said Kresner. “Changing them on a level that deep is something I definitely never thought about when I was creating the site, but it’s just as awesome if you can form a relationship with someone that makes them a happier person. Helping people get married, but also helping them fill time in their life with happy interactions is what it’s all about.”</p><p>With the help of Kresner, relationships have been formed all over the world.</p><p>Working with ClimbFind, Kresner traveled “all around the UK, all the way down the west coast, and in New York, Boulder, and Australia.” He even spent some time living in a hostel in Bariloche, a little town in the Andes Mountains in Argentina.</p><p>“Just like being in the right environment to start your company, you being in the right state to get the most out of an environment is pretty important. I’d seriously consider taking a break from the city and relocating to Patagonia or Southeast Asia and living an amazing lifestyle for a couple months. The only problem with moving down there is you’re isolated. If you’re building your team still and your idea isn’t quite off the ground, it’s completely detrimental to be somewhere like that. There’s a time and a place for everything,” said Kresner.</p><p>I was definitely in the right place at the right time when I met Kresner. His drive and focus on AirPair’s success inspires me.</p><p>“I earn that next step, and then I try to look forward one step beyond that,” said Kresner.</p><p>His personal mantra this year is: “The journey of a thousand miles continues with one more step.” While focused on the next step or two for AirPair, Kresner makes sure that he is constantly pushing toward his vision to keep the company moving where he wants to go.</p><p>“I think there’s philosophy and vision, and then there’s an idea. Ideas should morph and evolve as they go, so hopefully we’ve got a great vision and we can execute. The idea is something that just changes as we go,” said Kresner.</p><p>I look forward to seeing all the amazing things that will be coming out of AirPair’s studios in the near future. The idea is great, but the people executing on that idea are both skilled and driven. Their success isn’t a matter of if, but of when.</p><p><a href="https://twitter.com/dnsbty"><em>Dennis Beatty</em></a><em> is a BYU student from San Antonio, Texas who has been building companies around his ideas since high school. When he isn’t programming or studying, </em><a href="http://dennisbeatty.com/"><em>Dennis</em></a><em> loves to meet new people, cook them awesome food, and then beat them at tennis while their stomach is full.</em></p><p><strong>Published 4/5/2014</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f7cef9d486b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/beehive-startups/what-i-learned-from-airpair-founder-jonathon-kresner-while-in-san-francisco-9f7cef9d486b">What I Learned From AirPair Founder Jonathon Kresner While in San Francisco</a> was originally published in <a href="https://medium.com/beehive-startups">Beehive Startups</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>