<?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[Luftzig - Medium]]></title>
        <description><![CDATA[Functional Programming, Web Dev and Games - Medium]]></description>
        <link>https://medium.com/luftzig?source=rss----98aa7d946278---4</link>
        <image>
            <url>https://cdn-images-1.medium.com/proxy/1*TGH72Nnw24QL3iV9IOm4VA.png</url>
            <title>Luftzig - Medium</title>
            <link>https://medium.com/luftzig?source=rss----98aa7d946278---4</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 18:29:45 GMT</lastBuildDate>
        <atom:link href="https://medium.com/feed/luftzig" rel="self" type="application/rss+xml"/>
        <webMaster><![CDATA[yourfriends@medium.com]]></webMaster>
        <atom:link href="http://medium.superfeedr.com/" rel="hub"/>
        <item>
            <title><![CDATA[Cat Racing, Or: How to Handle Requests Life Cycle in Elm, Part III — Representing Request Life…]]></title>
            <link>https://medium.com/luftzig/cat-racing-or-how-to-handle-requests-life-cycle-in-elm-part-iii-representing-request-life-568cebd08d66?source=rss----98aa7d946278---4</link>
            <guid isPermaLink="false">https://medium.com/p/568cebd08d66</guid>
            <category><![CDATA[elm]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Yoav Luft]]></dc:creator>
            <pubDate>Sat, 21 Oct 2017 17:32:01 GMT</pubDate>
            <atom:updated>2017-10-21T17:32:01.153Z</atom:updated>
            <content:encoded><![CDATA[<h3>Cat Racing, Or: How to Handle Requests Life Cycle in Elm, Part III — Representing Request Life Cycle with Types.</h3><p>In this third and final part of my <a href="https://medium.com/luftzig/cat-racing-or-how-to-handle-requests-life-cycle-in-elm-part-i-f01bdfa5098d">Cat Racing HTTP Requests</a> tutorial we’ll finally see how we can use Elm’s advanced type system to represent the state of things in our application.</p><h3>Previously…</h3><p>So far, we had created a simple application that has only one page in which there’s a form that can be submitted to the server. <a href="https://gist.github.com/Luftzig/ae56c4c9625acc50f4a0e4a3d1f6be11">Have a look at the code</a>.</p><h3>Goal</h3><p>Our goal for this part is simple: To represent the state of the form. But what does it mean, exactly? Elm programming is filled with <a href="https://en.wikipedia.org/wiki/K%C5%8Dan">Kōan</a> like questions, such as “What is a State?” and “What is a state of form?”.</p><p>So what is a the state of a form? There is no one right answer, and we can consider several, for example:</p><ul><li>It is the current data being represented in the form.</li><li>It is whether the inputted data is valid or not.</li><li>It is whether the form had been sent to server or not.</li><li>It is whether the form had been sent, and whether the server had replied.</li></ul><p>I could have probably think on several more, but we can stop here. For our purpose, we’ll just choose something as our state. We’ll define:</p><blockquote>The state of our form is the following: <br>1. Whether the user had inputted anything into the form, or modified the data received from the server. <br>2. Whether the form had been sent to the server or not. <br>3. Whether the server had accepted the request, or some error had occurred.</blockquote><p>Now we can think about how to represent these different states. In Elm, we can represent everything with types, and we had seen that we can create a type with several different constructors, of values. Lets construct a FormState type:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a40020e3740397c3700285dd6075ba31/href">https://medium.com/media/a40020e3740397c3700285dd6075ba31/href</a></iframe><h3>Organizing Our Model</h3><p>We need to decide where to use this new state type. Since our model is very simple, there are only two options:</p><ol><li>Adding it to the Model type</li><li>Adding it to the Cat type</li></ol><p>Lets consider the first one. If we add it to the Model type, we are now limiting ourselves to just one form, one request in a time. So it doesn’t look like a good fit.</p><p>But if we add it to the Cat type, we can have as many Cat records as we want, each with its own state. A much better fit.</p><p>On the other hand, is a Cat object inherently stateful? Consider this:</p><pre>type alias Cat =<br>    { name : String<br>    , id : Maybe String<br>    , score : Maybe Int<br>    , state : FormState<br>    }</pre><p>Doesn’t the state field seems a little out of place to you? name, id and score are all fields that describe a Cat, both at the front-end and at the back-end. state is only used for some book keeping in the front-end.</p><p>We should find some way to decouple the two concepts: the data representing a cat, and the data representing the state of the form, related to some cat.</p><h3>Parametric Types</h3><p>We had already seen parametric types in Elm. We seen them when we first encountered the Maybe type, defined as</p><pre>type Maybe a = Just a<br>             | Nothing</pre><p>Or the Result type, that has two parameters. By now, we should know that this a means “any type”, so we can define Maybe String or Maybe Cat. We used that for some book-keeping about the “inner” type, for example, in Maybe Cat we know that we either have a Cat, or we have Nothing.</p><p>Now we’re going to define our own parametric type for handling state. It is in fact very simple, we’re just going to add a type parameter to our existing definition of a state, and rename it slightly.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1353b1d0c1b70089766847ec755c7b2a/href">https://medium.com/media/1353b1d0c1b70089766847ec755c7b2a/href</a></iframe><p>We can now redefine our model to make use of our new Stateful type:</p><pre>type alias Model =<br>    { cat : Stateful Cat }</pre><p>And of course, this Stateful type is agile enough to be used in various other places, for example, maybe we have several cats:</p><pre>type alias Model = { cats : List (Stateful Cat) }</pre><p>Or maybe just the Cat being edited should be stateful, and the rest not:</p><pre>type alias Model = <br>    { cats : List Cat<br>    , editing: Stateful Cat<br>    }</pre><p>Or maybe we have both a Cat and a Jockey?</p><pre>type alias Model =<br>    { cat : Stateful Cat<br>    , jockey: Stateful Jockey<br>    }</pre><h3>How Do We Use It?</h3><p>We had decided to use our Stateful a type, and we should now update our code accordingly. But at first glance, it seems complicated. Should our update function know how to update the state? And there are all those parts that expect to handle a Cat, not a Stateful Cat, what should we do about them?</p><p>The answer is simple: write some functions to work with Stateful! First and foremost, we need to extract the Cat from the Stateful Cat. That’s easy, because no matter what the state of Stateful a it is, it always has an inner value a.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12e96291c56c285f75b5473d261404e5/href">https://medium.com/media/12e96291c56c285f75b5473d261404e5/href</a></iframe><p>We need to pattern match on every possible constructor of Stateful but other than that, getting the underlying value is pretty straight forward.</p><p>What about updating it? Again, we should create some helper function for that. We’ll call it mapStateful:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49f436abed855eb36e196b44e810a094/href">https://medium.com/media/49f436abed855eb36e196b44e810a094/href</a></iframe><p>This one is a bit more complicated. It takes two values, a function from a to a and a Stateful a. It will then apply the function on the inner a value and return the new Stateful. We can also see that this mapping is state-aware, for example, if the state was NotChanged then after we map over it, it will become Changed. If we’re Waiting or had failed, we do not allow mapping at all.</p><p>This pattern of creating a mapping function is very common. Consider for example List.map: It is defined as map : (a -&gt; b) -&gt; List a -&gt; List b. This a -&gt; b part is telling us the we may change the underlying type of the list, transforming a list of integers to a list of booleans, for example. But in our Stateful type we do not allow the underlying type to change.</p><p>Finally, we might want to change the state and the data based on some logic. A good example is when the server returns a response. Our code will now have to decide whether the request had been successful or not, and maybe use the old value in some way too.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/446afb48a766c3e4f0d331bc8f752a57/href">https://medium.com/media/446afb48a766c3e4f0d331bc8f752a57/href</a></iframe><p>Our updateState is very similar to our mapStateful function, but now the user has to supply a function that maps the inner value a to some new Stateful a type.</p><h3>Putting Stateful Into Use</h3><p>Equipped with our Stateful type and its functions, we are ready to update our update function.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ab455402860edfb486ec5fa4629b4f09/href">https://medium.com/media/ab455402860edfb486ec5fa4629b4f09/href</a></iframe><p>Lets examine each branch separately, starting with ChangeName:</p><p>In ChangeName we used setName to rename our cat. The type of setName is String -&gt; Cat -&gt; Cat. For modifying a value inside a Stateful we need to supply mapStateful with a a -&gt; a function as its first argument. setName newName is such a function, because in Elm functions can be partially applied.</p><p>In SaveChanges we need to update that we are now waiting for the server to respond. We can use updateState for that. The first argument to updateState has to be a a -&gt; Stateful a function. Amazingly, the type constructor Waiting of Stateful is such a function!</p><p>In UpdateFailed we need to do some mix &amp; matching. The server had returned an error, and we want to save the value before submitting. We will then construct a completely new Stateful Cat value with the type constructor Failed which expects an Http.Error and a Cat. We’ll get the Cat value from the current model.cat by using getValue.</p><p>Finally, in UpdateSucceeded we don’t care about the old value of model.cat. So we’ll just construct a new one with the result returned from the server.</p><h3>Summary</h3><p>Our three parts journey in handling requests and their life cycle in Elm comes now to a conclusion. We had seen how to create a simple form program in Elm in the first part; We had seen how to communicate with the server in the second part; And today we seen how we can use types to better structure our program.</p><p>I wish you a smooth sail in seas of Elm. It is wonderful language that had changed the way I view front-end programming completely.</p><p>Until next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=568cebd08d66" width="1" height="1" alt=""><hr><p><a href="https://medium.com/luftzig/cat-racing-or-how-to-handle-requests-life-cycle-in-elm-part-iii-representing-request-life-568cebd08d66">Cat Racing, Or: How to Handle Requests Life Cycle in Elm, Part III — Representing Request Life…</a> was originally published in <a href="https://medium.com/luftzig">Luftzig</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cat Racing, Or: How to Handle Requests Life Cycle in Elm, Part II — Communicating with the Server]]></title>
            <link>https://medium.com/luftzig/cat-racing-or-how-to-handle-requests-life-cycle-in-elm-part-ii-communicating-with-the-server-a85e870e1318?source=rss----98aa7d946278---4</link>
            <guid isPermaLink="false">https://medium.com/p/a85e870e1318</guid>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[elm]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Yoav Luft]]></dc:creator>
            <pubDate>Fri, 13 Oct 2017 14:16:36 GMT</pubDate>
            <atom:updated>2017-10-21T17:32:40.081Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article we’re going to continue our journey in Elm language request forms. <a href="https://medium.com/luftzig/cat-racing-or-how-to-handle-requests-life-cycle-in-elm-part-i-f01bdfa5098d">Last time</a> we created a form with a text input field, a field for data from the server and a submit button that crashes the app. Today, we’re going to fix that!</p><h3>Recap</h3><p>Our small Cat Racing App has, like all Elm programs, a Model to represent our data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ff4a3b3fda69c5f6073f32694e22f0fa/href">https://medium.com/media/ff4a3b3fda69c5f6073f32694e22f0fa/href</a></iframe><p>We have a view function to construct HTML from our model</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/734aede516bfca600b36de1b9ab689d2/href">https://medium.com/media/734aede516bfca600b36de1b9ab689d2/href</a></iframe><p>We have Messages and an update function to handle these messages. Messages are being generated from the view when the user does stuff, like entering text into the the text field, or clicking a button</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d1bb336c4a5505d089c3ff57855805e5/href">https://medium.com/media/d1bb336c4a5505d089c3ff57855805e5/href</a></iframe><p>Finally, we connected all those components using an Elm program, like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/220e258e8e4c9d29fcad6898cf5d5fed/href">https://medium.com/media/220e258e8e4c9d29fcad6898cf5d5fed/href</a></iframe><h3>Giving Commands</h3><p>You might have wondered why the signature of our update function is update : Message -&gt; Model -&gt; (Model, Cmd Message). Why do we return a tuple? What is this Cmd type?</p><p>This Cmd type is all about side effects, and to explain that we’ll start with a short discussion on the theory of functional programming.</p><h3>Side Effects and Functions</h3><p>It the world of functional programming, we make a clear distinction between a function which maps some value to some other value, and a side effect, which is an effect that changes something out there in the world.</p><p>A function is simple a mapping: for example, give me a number, and I’ll map it to a string representing this number. In Elm we use function signature to say just that: toString : Int -&gt; String. Our function cannot change its input, neither can it change anything else in our program. It can only return a value based on its input, and that’s it. We cannot, for example, assign a value because this would change something in the outside world. We cannot read a value from a keyboard, for example, because having read this value we had again, changed something in the world. These are all side effects, which Elm does not allow in functions.</p><p>But, you might think, if we can’t change anything, neither by writing values or by reading them from some input, how can our program ever do something useful other than simple calculations?</p><p>The truth is that all functional languages allow side effects. They just allow them in a very limited and well checked context. A large number of annoyingly hard to debug bugs are the result of unchecked side effects, so we try to limit them, keep them guarded, watched, and checked to avoid these problems.</p><h3>Side Effects in Elm</h3><p>In Elm, we allow side effects through several channels, two of which we already met, these are</p><ol><li>View function</li><li>Update function</li><li>Commands</li><li>Subscriptions</li></ol><p>We already met our view function. It returns some data structure of type Html msg that is being used by the Elm architecture code to update the actual DOM of the page. It is the primary output side effect of Elm programs.</p><p>We also met our update function. It accepts messages that can come from several channels, such as DOM events, timers, HTTP requests and so on. We use it to update the model, and in turn to update the view from the model. This is the primary way in an Elm program to handle input side effects.</p><p>Commands, our topic for today, are used to instruct the Elm architecture to do stuff which doesn’t fit well with the update-model-view design. A common use case we’ll see today is doing HTTP requests. Other use cases are querying data from the browser (for example, the size of window), generating random values or reading and saving data to local storage.</p><p>Finally, subscriptions are a way for us to ask the Elm architecture to provide us with messages when some event happens. A common use case is to receive a message every time a keyboard key is pushed, or on every mouse click, or at determined intervals.</p><h3>Performing HTTP Requests</h3><p>In order to send an HTTP Request (a side effect) we need to do the following: Ask the Elm architecture to initiate a side effect; Define the Messages that will be used to inform us on the state of our request; Handle those message in our update function.</p><p>The Cmd msg type is how we ask the Elm architecture to perform side effects. We’ll see that the <a href="http://package.elm-lang.org/packages/elm-lang/http/1.0.0/Http">elm-lang/http</a> package defines a send function as</p><pre>send : (Result Error a -&gt; msg) -&gt; Request a -&gt; Cmd msg</pre><p>We can use it to initiate an HTTP request. Lets examine it closely:</p><p>The first argument for send is a function mapping a Result Error a into a msg. We already now that we should substitute msg for our actual Message type. What is Result? What is a valid a that parametrizes Result? We can find Error in the HTTP package, and it represents all kinds of possible HTTP related errors.</p><p>The second argument is a Request a. We know the a from Result is the same a from Request. We’ll also notice that Request is defined in the HTTP package. It is an opaque type, which means that the implementation details are kept hidden from us. Also in the HTTP package we can find various functions that return a Request a. One of them is the post function</p><pre>post : String -&gt; Body -&gt; Decoder a -&gt; Request a</pre><p>This is an important clue! We now know that a Request a is something we create from a String, a Body and a Decoder of a. So a should be something that we decode from out HTTP request. In fact, it is the type of the decoded HTTP response.</p><h3>Interlude: the Result type</h3><p>The Result type is used to represent the result of some calculation that might succeed or fail. It is similar to Maybe in that represents two possible outcomes. It is defined as:</p><pre>type Result error value<br>    = Ok value<br>    | Err error</pre><p>We can pattern match on it find our if some computation had succeed or not.</p><h3>Sketching Up Our Request</h3><p>Let us sketch some of this up in out update function. We need:</p><ol><li>To create a request and then send it.</li><li>To create messages for handling the response.</li><li>To construct the request Body.</li><li>To decode to response body to some type.</li></ol><p>We’ll decide for now that we don’t care about why a request had failed. We can start by updating our Message type and our update function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe81e4cb6210acd69ea969c0235a6ca0/href">https://medium.com/media/fe81e4cb6210acd69ea969c0235a6ca0/href</a></iframe><p>We now have 2 more messages, one for a successful update and one for a failed one. We handle these in our update function by using the Cat we got back from the server on success, and printing to log on failure.</p><p>Also, we can now handle the SaveChanges Cat message by returning a new Cmd Message. It will not change the model, and we’ll create a new function sendUpdateRequest that will take a Cat and turn it into a Cmd Message.</p><h3>Constructing Requests</h3><p>We’ll start constructing our request by writing up something, and then fill in the blanks. First, we know that we need this function:</p><pre>sendUpdateRequest : Cat -&gt; Cmd Message</pre><p>We also know that we’re going to implement it using send from the HTTP package. Let’s sketch something up:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/08c820e64e641b22f7dd64b75bf350e9/href">https://medium.com/media/08c820e64e641b22f7dd64b75bf350e9/href</a></iframe><p>We know that send takes a Result Error a -&gt; msg and a Request a. Our a is a Cat and our msg is Message. We know that we can use post to create a request. Remember that the &lt;| operator is used instead of parentheses.</p><p>We’re now left with several blank to fill. We’ll start with createMessage which is the easiest</p><pre>createMessage : Result Error Cat -&gt; Message<br>createMessage result =<br>  case result of<br>    Ok cat -&gt; UpdateSucceded cat<br>    Err error -&gt; UpdateFailed error</pre><p>Simple, right? We just make sure that the signatures match and everything just flows from there!</p><p>Next, we have createBody and decodeResponse. We know that createBody should have this signature: createBody : Cat -&gt; Body but we’re not sure what Body is. We also know that decodeResponse should have the signature of decodeResponse : Decoder Cat, but we don’t know what Decoder is. In fact, these two functions are an encoder and decoder, which take one representation of data and turn it into another, and vice-versa.</p><h3>Encoding and Decoding Data</h3><p>Encoding and Decoding is the process of taking one representation of our data, usually its in memory representation, and turning it into some textual or binary representation that is easy to transfer over the wire (encoding); And taking some binary or textual representation of data from the wire and turning it into a representation our program can use.</p><p>One common format we’ll use today is JSON, or the JavaScript Object Notation. Elm has some great facilities to handle JSON values which do not just encode and decode (which in fact the browser can do for us), but also, or especially, check the correctness of our values.</p><p>We’ll start with encoding. If we’ll look at the HTTP package, we’ll see that it has the function jsonBody : Value -&gt; Body. Value is from the Json built-in module and it represents some valid JSON. Using utility functions from the Json module we can construct our createBody function</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7f201e3cf289c4f01c0c8ef2d0cba39/href">https://medium.com/media/a7f201e3cf289c4f01c0c8ef2d0cba39/href</a></iframe><p>I will not go into depth on how encoders and decoders work. I will only try to explain why they are useful.</p><p>Our encoding function is used as a definition of what should be sent. We can read it as saying</p><blockquote>Send an object. It has three fields, first one is called “name” and it should be a string. Second is called “id” and it can be either null or a string; third is “score” and it can be either null or an integer.</blockquote><p>This is useful because lets say that at some point we decide that score is no longer a single number, but a list of numbers. The compilation will fail, because in our encode function, we promised to encode “score” as a single number. If we were using JavaScript’s JSON.stringify() function we would then only find out at runtime that we sent something wrong to our server.</p><p>A decoder works in a similar fashion: We define what we expect our data to be, and then it runs some code to validate it. Our decodeResponse function looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ca19af8808dd5fbaa850c7eb7b95406/href">https://medium.com/media/5ca19af8808dd5fbaa850c7eb7b95406/href</a></iframe><p>Again, we’re telling it what the data should be. It should have 3 fields, “name”, “score” and “id”. “name” and “id” are strings, “score” is an integer. “score” and “id” might not have a value, but they must included in the message.</p><p>The Json.Decode module defines some functions that can use a decoder, for example decodeString : Decoder a -&gt; String -&gt; Result String a. We can see from its signature that it might fail. The JSON in the string might be missing some fields, or have illegal value in them, or might not be a JSON at all! This can help us avoid some sneaky bugs where the backend team changes the interface and fails to communicate it to the frontend team.</p><h3>Summary</h3><p>In this part we’ve seen how we can communicate with a remote server in an Elm program. We had learned about side effects, and how they are being allowed in Elm only through limited, well checked interfaces to avoid bugs. We had learned how to construct HTTP requests and how to handle the response. Finally, we had seen JSON encoders and decoders, which help us catch easy-to-miss bugs when the representation of our data changes.</p><p>In the <a href="https://medium.com/luftzig/cat-racing-or-how-to-handle-requests-life-cycle-in-elm-part-iii-representing-request-life-568cebd08d66">next part</a> we’ll finally get to title of the series, when will see how we can use types to handle the different states of requests.</p><p>Until next time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a85e870e1318" width="1" height="1" alt=""><hr><p><a href="https://medium.com/luftzig/cat-racing-or-how-to-handle-requests-life-cycle-in-elm-part-ii-communicating-with-the-server-a85e870e1318">Cat Racing, Or: How to Handle Requests Life Cycle in Elm, Part II — Communicating with the Server</a> was originally published in <a href="https://medium.com/luftzig">Luftzig</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cat Racing, or: How to Handle Requests Life Cycle in Elm — Part I]]></title>
            <link>https://medium.com/luftzig/cat-racing-or-how-to-handle-requests-life-cycle-in-elm-part-i-f01bdfa5098d?source=rss----98aa7d946278---4</link>
            <guid isPermaLink="false">https://medium.com/p/f01bdfa5098d</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[elm]]></category>
            <dc:creator><![CDATA[Yoav Luft]]></dc:creator>
            <pubDate>Sat, 23 Sep 2017 14:16:55 GMT</pubDate>
            <atom:updated>2017-10-21T17:31:09.478Z</atom:updated>
            <content:encoded><![CDATA[<p>Part one out of three.</p><p>This is a written adaption of a talk I gave in <a href="https://www.meetup.com/Elm-TLV/">Elm-TLV</a> meetup. I’ll go through the process of creating a simple form, sending request to a server and managing request life-cycle using <a href="https://en.wikipedia.org/wiki/Abstract_data_type">ADT</a>s. Elm beginners should feel at home!</p><h3>Getting started with an Elm Program</h3><p>Our form will be about registering a cat for <a href="http://grim-fandango.wikia.com/wiki/Cat">cat racing</a>. Our racing cat for now will only have a name, an ID (that was created by the server) and a possible score if it had already been to some races. We’ll call those fields our model, and it will be the basis for our program:</p><pre>type alias Cat =<br>  { name : String<br>  , id: Maybe String<br>  , score: Maybe Integer<br>  }</pre><pre>type alias Model =<br>  { cat : Cat<br>  }</pre><p>We defined two new record types. A record has named fields, for our Cat those are “name”, “id” and “score”, and for our Model it is only “cat”. When defining a record we must specify the types of the fields. We used for our Cat a string for a name, a Maybe string for an ID and a Maybe integer for the score. The Maybe a type (for any type a) is used to say that this field can either have some value of type a, i.e. a string or integer, or have no value at all.</p><h3>View Function</h3><p>We’ll proceed to our view function. Our view function is in charge of taking a model and rendering it to HTML.</p><pre>view : Model -&gt; Html.Html Message<br>view model =<br>    form [ ]<br>        [ div []<br>            [ label [] [text &quot;Name&quot;]<br>            , input [ ] []<br>            ]<br>        , div []<br>            [ label [] [text &quot;Score&quot;]<br>            ]<br>        , div []<br>            [ button [ type_ &quot;submit&quot; ] [text &quot;Update&quot;]<br>            ]<br>        , div [] [text &lt;| toString model.cat ]<br>        ]</pre><p>We use type annotations to tell the compiler what we expected the function to do: “Model -&gt; Html.Html Message”, or in English “Turn a Model to (Html Message)”.</p><p>In the root of our view is a form. It has 4 div: First one is a labeled text box for the name, second is for the score, third is for a button and the last one will just print out our Cat to make it easy for us to see that our program is working.</p><h3>Update Function</h3><p>Next, is an update function. An update function is a function that receives messages from the view and updates the Model accordingly. So for an update function we first need to define messages:</p><pre>type Message = ChangeName String<br>             | SaveChanges Cat</pre><p>This time we used the type instead of type alias and we created a Message type. This type has 2 possible constructors: ChangeName String and SaveChanges Cat. We can later <a href="https://csmith111.gitbooks.io/functional-reactive-programming-with-elm/content/section2/PatternMatching.html">pattern-match</a> on those constructors and the values they contain for branching. Don’t worry if you don’t get that now, we’ll see it being used soon enough. You can think of the pipe as meaning “Message is either ChangeName (containing a String in it) <strong>or</strong> SaveChanges (containing a Cat).”</p><p>By the way, that Message type is the one from Html.Html Message we used in our view function. It tells us that our view is going to generate messages of type Message.</p><p>Now that we know what our messages are, we can write up an update function to handle them.</p><pre>update : Message -&gt; Model -&gt; (Model, Cmd Message)<br>update msg model =<br>  case msg of<br>    ChangeName newName -&gt;<br>      ({ model | cat = setName newName model.cat }<br>      , Cmd.none<br>      )</pre><pre>    SaveChanges cat -&gt;<br>      Debug.crash &quot;We don&#39;t know how to save!&quot;</pre><p>In Elm and other strongly typed functional languages, we usually start from reading the function’s signature, or type. A wisely constructed function is one that we can understand just from its name and types. Our update function is taking a Message and a Model and returns a new tuple of a Model and something called Cmd that we’ll discuss later.</p><p>We use pattern matching to handle our different message, using the case x of construct. It has several pattern -&gt; code blocks. On the left side is a pattern, usually a type constructor and values contained in it, and on the right side is some result. The Elm compiler is going to check that we had covered all possible values so we’ll never forget some weird corner case.</p><p>Our first block will change the name of our cat, by creating a new copy of model with its cat field modified. We used an helper function to modify the cat field, but that’s not required.</p><p>Our second block handles SaveChanges by… well, crashing. Because we don’t know how to save yet. We had to include some implementation of this case, or our code wouldn’t compile.</p><h3>Sending messages</h3><p>We have our model, view and update, but in order to get anything working we need to have our view to send messages. We’ll use some built-in functions such as onSubmit and onInput to do so:</p><pre>view : Model -&gt; Html.Html Message<br>view model =<br>    form [ ]<br>        [ div [ <strong>onSubmit &lt;| SaveChanges model.cat</strong> ]<br>            [ label [] [text &quot;Name&quot;]<br>            , input [ <strong>onInput ChangeName</strong> ] []<br>            ]<br>        , div []<br>            [ label [] [text &quot;Score&quot;]<br>            ]<br>        , div []<br>            [ button [ type_ &quot;submit&quot; ] [text &quot;Update&quot;]<br>            ]<br>        , div [] [text &lt;| toString model.cat ]<br>        ]</pre><p>onSubmit has the signature of onSubmit: Message -&gt; Attribute Message and onInput is (String -&gt; Message) -&gt; Attribute Message which means that its first argument is function that takes a string and returns a message.</p><p>This funny &lt;| operator is called a function application operator. We’re using it instead of putting the right side of the argument in parentheses. Those two expressions are equal: onSubmit &lt;| SaveChanges model.cat and onSubmit (SaveChanges model.cat). Using one over the other is mostly about style rather then correctness.</p><h3>Wrapping it together</h3><p>We need to combine all the parts of our program into a program. We’re going to declare a main function using the program built-in:</p><pre>main = program<br>    { view = view<br>    , update = update<br>    , subscriptions = Sub.none<br>    , init = (initModel, Cmd.none)<br>    }</pre><p>We’re not going to use subscriptions in this example. Also, I’m not including initModel because it’s just an initial value of our model.</p><p>We can compile and run our program with the elm command line. Just run elm make Main.elm and if your code is correct it will output index.html with our program. It should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*gKPL7VYu3M3OVoQws0zO8g.png" /></figure><h3>Concluding Part I</h3><p>We now have a form with a single field representing some model, and a submit button. In the <a href="https://medium.com/luftzig/cat-racing-or-how-to-handle-requests-life-cycle-in-elm-part-ii-communicating-with-the-server-a85e870e1318">next part</a> we’re going to send our model to the server, and update our local model from the server reply.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f01bdfa5098d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/luftzig/cat-racing-or-how-to-handle-requests-life-cycle-in-elm-part-i-f01bdfa5098d">Cat Racing, or: How to Handle Requests Life Cycle in Elm — Part I</a> was originally published in <a href="https://medium.com/luftzig">Luftzig</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sequencing Enumerators: Better, Stronger, Faster!]]></title>
            <link>https://medium.com/luftzig/sequencing-enumerators-better-stronger-faster-8ef1f8f1cad0?source=rss----98aa7d946278---4</link>
            <guid isPermaLink="false">https://medium.com/p/8ef1f8f1cad0</guid>
            <dc:creator><![CDATA[Yoav Luft]]></dc:creator>
            <pubDate>Sat, 12 Aug 2017 13:06:26 GMT</pubDate>
            <atom:updated>2017-09-16T08:24:45.109Z</atom:updated>
            <content:encoded><![CDATA[<p>In a previous <a href="https://missingclosure.wordpress.com/2017/08/09/sequencing-background-calls-in-unity/">post</a> a I talked about how we can improve our lives when working with IEnumerator in C#. It is especially important because Unity overloads the meaning of IEnumerator for being used in coroutines.</p><p>In the last post we created two helper functions to work with IEnumerators.</p><pre>class Sequence<br>{<br>  public static IEnumeretor Chain(IEnumerable&lt;IEnumerator&gt; enumerators)<br>  {<br>    foreach (IEnumerator e in enumerators)<br>    {<br>      while (e.MoveNext()) yield return e.Current;<br>    }<br>  }</pre><pre>public static IEnumerator Chain(params IEnumerator[] enumerators)<br>  {<br>    IEnumerator inner = Chain(enumerators);<br>    while (inner.MoveNext()) yield return inner.Current;<br>  }<br>  <br>  public static IEnumerator FromAction(Action action)<br>  {<br>    action();<br>    yield break;<br>  }<br>}<br>This was nice, but I wanted more. While these helpers proved to be helpful, I was hoping for a more flowing kind of interface. So, I tried to further improve on them by defining a new class inheriting from IEnumerator.</pre><pre>We&#39;ll call this class a Sequence, and we&#39;ll start by delegating all functionality to an actual IEnumerator that will be wrapped by our new class:</pre><pre>class Sequence : IEnumerator<br>{<br>  private readonly IEnumerator _inner;<br>  <br>  object IEnumerator.Current<br>  {<br>    get { return _inner.Current }<br>  }</pre><pre>public bool MoveNext()<br>  {<br>    return _inner.MoveNext();<br>  }</pre><pre>public void Reset()<br>  {<br>    _inner.Reset();<br>  }<br>}<br>Next, we&#39;ll need some way to create new sequences. Let&#39;s create 2 handy constructors</pre><pre>class Sequence : IEnumerator<br>{<br>  // ...<br>  public Sequence(IEnumerator enumerator)<br>  {<br>    _inner = enumerator;<br>  }</pre><pre>public Sequence(Action action)<br>  {<br>    _inner = FromAction(action);<br>  }</pre><pre>public static Sequence From(IEnumerator e) { return new Sequence(e); }</pre><pre>public static Sequence From(Action a) { return new Sequence(a); }<br>}<br>(The static constructor are just a convenience, they are not really necessary for understanding our wrapper.)</pre><pre>Now what we have our wrapper, we can add some new functionality to it to make our life easier. Basically, we want it to be used in order to combine enumerators to each other without creating a &quot;Pyramid of Doom&quot; kind of code. Well add method to do just that:</pre><pre>// class Sequence ...<br>public Sequence AndThen(IEnumerator enumerator)<br>{<br>  return Sequence.From(Chain(_inner, enumerator));<br>}</pre><pre>public Sequence AndThen(Action action)<br>{<br>  return AndThen(From(action));<br>}<br>Why I named it &quot;AndThen&quot;? Because we&#39;re using the wrapper to sequence actions. So something such as Sequence.From(Animate(...)).AndThen(Spin(...)) reads very naturally in my opinion. Also, the Elm programming language uses &quot;AndThen&quot; quite often and it is one of the friendliest programming languages I had ever used, so I&#39;ll use their convention.</pre><pre>Our first AndThen is pretty straight forward: We create a new sequence by chaining to our existing sequence the argument enumerator.</pre><pre>The other implementation is a bit more complicated, but only because it reuses code we had just seen for the first time. Starting from the innermost parentheses, we just have an action. We use our static From constructor to turn this action into a Sequence; Since a Sequence is a super class of IEnumerator, we can then pass it to the first implementation of AndThen and we&#39;re done!</pre><pre>The complete Sequence source code is <a href="https://gist.github.com/Luftzig/37c7401cd2227b90a60d5158eddca70e">available on github</a>!</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ef1f8f1cad0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/luftzig/sequencing-enumerators-better-stronger-faster-8ef1f8f1cad0">Sequencing Enumerators: Better, Stronger, Faster!</a> was originally published in <a href="https://medium.com/luftzig">Luftzig</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sequencing Background Calls in Unity]]></title>
            <link>https://medium.com/luftzig/sequencing-background-calls-in-unity-4fc40b4ffd3e?source=rss----98aa7d946278---4</link>
            <guid isPermaLink="false">https://medium.com/p/4fc40b4ffd3e</guid>
            <dc:creator><![CDATA[Yoav Luft]]></dc:creator>
            <pubDate>Wed, 09 Aug 2017 14:04:11 GMT</pubDate>
            <atom:updated>2017-09-16T08:24:44.111Z</atom:updated>
            <content:encoded><![CDATA[<p>We’re using <a href="https://unity3d.com/">Unity</a> to develop <a href="https://www.facebook.com/ZenKittyGames/">Zen Garden</a>. On the one hand, the engine and framework provide a lot of things out of the box, and C# is a pretty decent programming language, at least as far as Enterprise Object Oriented languages go.</p><p>On the other hand, programming in Unity feels like going 10 years back in terms of dependencies management (there is none), language feature (it support an old variant of C#) and APIs.</p><h3>Doing Stuff in the Background</h3><p>One such API is the Coroutines API for running background tasks. Turns out that working with threads is rather awkward in unity, due to the fact that many APIs can only be called from the main thread. So instead, unity uses a “Coroutine” based concurrency model.</p><pre>void StartCoroutine(IEnumerator coroutine)</pre><p>will run the <a href="https://msdn.microsoft.com/en-us/library/system.collections.ienumerator(v=vs.110).aspx">IEnumerator</a> in an asynchronous manner. One common use for coroutines is to do animations in scripting, for example:</p><pre>IEnumerator Animate(GameObject obj, Vector3 from, Vector3 to, Time time)<br>{<br>  Time accumulatedTime = 0;<br>  while (accumulatedTime &lt; time)<br>  {<br>    accumulatedTime += Time.deltaTime;<br>    obj.transform.position = Vector3.Lerp(from, to, accumulatedTime / time);<br>    yield return null;<br>  }<br>}</pre><p>The yield return null statement will turn any C# function to an <a href="https://en.wikipedia.org/wiki/Generator_(computer_programming)#C.23">iterator</a> (or generator) function. The compiler will automatically transform the function into a function that returns an IEnumerator object, that on each call to its MoveNext() method it will execute the function until it reaches a yield return x statement. The value of its Current field will be set to the value x yielded by the statement.</p><p>So by giving StartCoroutine an IEnumerator, we tell it to execute each step when the coroutine gets some time to run. This is a form of cooperative scheduling that works well on single threaded applications.</p><h3>A Coroutine of Coroutines?</h3><p>While using Unity’s coroutines we came across two kinds of problems. The first is how to sequence several coroutines together. For example, let us say we want to move an object through several points, how can we reuse Animate to do that?</p><pre>IEnumerator AnimatePath(GameObject obj, List&lt;Vector3&gt; path, List&lt;Time&gt; timing)<br>{<br>  for (int i = 0; i &lt; path.Length; i++)  // Unity doesn&#39;t support IEnumerable.Zip !<br>  {<br>    StartCoroutine(Animate(obj, obj.transform.position, path.Get(i), <br>      timing.Get(i));<br>    yield return null;<br>  }<br>}</pre><p>Now, I find the above code very awkward. We call StartCoroutine inside a StartCoroutine ? What if we need to use several functions? Is there a limit to this nesting? What if we need to refactor some, but not all of the code?</p><h3>Tell Me When You’re Done</h3><p>Another problem we had is doing something once a coroutine had completed. For example, let’s say that after we finished animating our object from one point to another, we want to perform some arbitrary action required by the calling function. This is impossible to do without rewriting Animate ! But maybe we can improve Animate to make this possible by making it accept a callback? Let&#39;s try!</p><pre>IEnumerator Animate(GameObject obj, Vector3 from, Vector3 to, Time time, Action callback)<br>{<br>  Time accumulatedTime = 0;<br>  while (accumulatedTime &lt; time)<br>  {<br>    accumulatedTime += Time.deltaTime;<br>    obj.transform.position = Vector3.Lerp(from, to, accumulatedTime / time);<br>    yield return null;<br>  }<br>  callback();<br>}</pre><p>The Action type is just any function that doesn&#39;t return a value. We should actually parametrize it (to state that it doesn&#39;t receive a value, too), but we&#39;ll leave that for now.</p><p>Now, our callback solution is decent, but slightly too coupled for my taste. Our Animate function now does two, unrelated things: It animates an object from one place to another, and it calls a callback.</p><p>And here’s an advanced observation: running 2 or more IEnumerator one after another is almost the same as calling a callback when one IEnumerator completes.</p><h3>Abstraction, I Choose You!</h3><p>Maybe we can abstract the two tasks from one another? Lets start by chaining IEnumerators together:</p><pre>IEnumerator Chain(params IEnumerator[] enumerators)<br>{<br>  foreach (IEnumerator enumerator in enumerators)<br>  {<br>    while (enumerator.MoveNext()) return yield enumerator.Current;<br>  }<br>}</pre><p>Not too complicated! We’re just yielding the values from each enumerator at its turn. When the first one completes (MoveNext() returns false ) we move to the next enumerator until we had consumed them all.</p><p>OK, we can use a slightly modified version of the code that accepts IEnumerable&lt;IEnumerator&gt; instead of a varying number of arguments and we can that refactor our AnimatePath function easily.</p><h3>From Actions To Enumerators</h3><p>What about callbacks? Let’s have a look at our callback from function again:</p><pre>IEnumerator Animate(GameObject obj, Vector3 from, Vector3 to, Time time, Action callback)<br>{<br>  // Do something with yield<br>  Time accumulatedTime = 0;<br>  while (accumulatedTime &lt; time)<br>  {<br>    accumulatedTime += Time.deltaTime;<br>    obj.transform.position = Vector3.Lerp(from, to, accumulatedTime / time);<br>    yield return null;<br>  }<br>  // Call the callback<br>  callback();<br>}</pre><p>It looks like we can turn any function into an IEnumerator quite easily by just adding a return yield null to the body of the function! Or maybe, just wrap it in a function that yields:</p><pre>IEnumerator ActionToIEnumerator(Action action)<br>{<br>  action();<br>  yield return null;<br>}</pre><p>That’s cool! So now we can combine the two things and transform any IEnumerator to an IEnumerator that calls a callback when it completes:</p><pre>IEnumerator WithCallback(IEnumerator enumerator, Action callback)<br>{<br>  return Chain(enumerator,<br>               ActionToIEnumerator(callback));<br>}</pre><p>Done! We improved our IEnumerators significantly, and we made coroutines a little bit nicer to work with as result!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4fc40b4ffd3e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/luftzig/sequencing-background-calls-in-unity-4fc40b4ffd3e">Sequencing Background Calls in Unity</a> was originally published in <a href="https://medium.com/luftzig">Luftzig</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Update!]]></title>
            <link>https://medium.com/luftzig/update-121e6ecab574?source=rss----98aa7d946278---4</link>
            <guid isPermaLink="false">https://medium.com/p/121e6ecab574</guid>
            <dc:creator><![CDATA[Yoav Luft]]></dc:creator>
            <pubDate>Sun, 23 Jul 2017 18:06:30 GMT</pubDate>
            <atom:updated>2017-09-16T08:24:45.982Z</atom:updated>
            <content:encoded><![CDATA[<p>I had not completed my post about observables, mostly because much had changed in the last 6 months.</p><p>To begin with, I quit my job at Matific. From the beginning I had my doubts about whether my ideal of a working environment is in par with Matific’s. Sadly, it turned out that we are not, so we went our separate ways. I wish Matific to keep on making great educational games.</p><p>Instead of finding another job, I became a freelancer! And not only that, my wonderful life-partner had set me up with some friends of her and we started a game studio. That’s a dream coming true for me, and our first game, <a href="https://www.facebook.com/ZenKittyGames/">Zen Garden</a>, should come out in the next few of months!</p><p>As a freelancer, I’ve picked up a lot of new technologies, and I plan to write about them. My first project used <a href="https://nodejs.org/">Node.JS</a>, <a href="http://elm-lang.org/">Elm</a> and <a href="https://www.docker.com/">Docker</a>, and it was a blast. I’m in love with Elm. I never enjoyed writing for the browser as I enjoyed it with Elm, which is not only a functional, type-safe language, it is also surprisingly similar to learn. Even more when you consider that its inspiration was <a href="https://www.haskell.org/">Haskell</a> (which I like, too, but its far from being easy to learn).</p><p>I plan to write shorter and more frequent posts from now on. Also, I’m considering migrating this blog to either Medium or my own hosting. Or maybe both? Time will tell.</p><p>Oh, and one more thing: I’m hoping to create a community of Functional Programming enthusiasts in Israel. I’m planning to do that by organizing more <a href="https://www.meetup.com/Elm-TLV/">Elm meet-ups </a>and around a <a href="https://www.facebook.com/groups/243758499361680/">functional programming in Hebrew</a> discussion group on Facebook. You’re welcome to join!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=121e6ecab574" width="1" height="1" alt=""><hr><p><a href="https://medium.com/luftzig/update-121e6ecab574">Update!</a> was originally published in <a href="https://medium.com/luftzig">Luftzig</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Angular 2 and Translations]]></title>
            <link>https://medium.com/luftzig/angular-2-and-translations-6ffbed570b2b?source=rss----98aa7d946278---4</link>
            <guid isPermaLink="false">https://medium.com/p/6ffbed570b2b</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[i18n]]></category>
            <dc:creator><![CDATA[Yoav Luft]]></dc:creator>
            <pubDate>Fri, 25 Nov 2016 14:44:19 GMT</pubDate>
            <atom:updated>2017-09-16T08:24:36.552Z</atom:updated>
            <content:encoded><![CDATA[<p>As part of our migration process from Angular 1 to Angular 2 we need to keep our support for international clients by providing localized version of our website. One important aspect of localization is providing a translated website.</p><p>It seems like when our current website was written there was no ready-made leading solution for translating Angular apps. We’re talking about version 1.2 and since then much had advanced, and when the website was split into to different websites the new one used <a href="https://angular-gettext.rocketeer.be/">angular-gettext</a> which works great with our gettext support at the backend side.</p><p>As for Angular 2, it seemed that at some point there was one solution developed by the angular team, which was recently abandoned for the ng-xi18n tool, as presented by the angular <a href="https://angular.io/docs/ts/latest/cookbook/i18n.html">internationalization guide</a>.</p><p>I was given the task of investigating proper internationalization and I started by following the guide, but quickly run into two problems:</p><ol><li>We are migrating from Angular 1 and for the time being we’ll have to support an hybrid app. The examples in the migration guide and the internationalization guide seem contradicting.</li><li>We use Webpack instead of SystemJS that is being used in the examples.</li></ol><p>Let’s start from the guide:</p><p>[code lang=”javascript”]<br>// app.component.html<br>&lt;h1 i18n=”Example message|should be witty”&gt;<br> Hi, I need to be translated!<br>&lt;/h1&gt;</p><p>// app.component.ts<br>import { Component } from ‘@angular/core’;</p><p>@Component({<br> moduleId: module.id,<br> selector: ‘my-app’,<br> templateUrl: ‘app.component.html’<br>})<br>export class AppComponent { }</p><p>// main.ts<br>import { platformBrowserDynamic } from ‘@angular/platform-browser-dynamic’;<br>import { AppModule } from ‘./app.module’;<br>platformBrowserDynamic().bootstrapModule(AppModule)<br>[/code]</p><p>And to that we add i18n-providers.ts, and use the translation while bootstrapping:</p><p>[code lang=”javascript”]<br>// i18n-providers.ts<br>import { TRANSLATIONS, TRANSLATIONS_FORMAT, LOCALE_ID } from ‘@angular/core’;<br>export function getTranslationProviders(): Promise&lt;Object[]&gt; {<br> const locale = document[‘locale’] as string;<br> const noProviders: Object[] = [];<br> if (!locale || locale === ‘en-US’) {<br> return Promise.resolve(noProviders);<br> }<br> const translationFile = `./locale/messages.${locale}.xlf`;<br> return getTranslationsWithSystemJs(translationFile)<br> .then( (translations: string ) =&gt; [<br> { provide: TRANSLATIONS, useValue: translations },<br> { provide: TRANSLATIONS_FORMAT, useValue: ‘xlf’ },<br> { provide: LOCALE_ID, useValue: locale }<br> ])<br> .catch(() =&gt; noProviders);<br>}</p><p>declare var System: any;<br>function getTranslationsWithSystemJs(file: string) {<br> return System.import(file + ‘!text’); // relies on text plugin<br>}</p><p>// main.ts<br>import { platformBrowserDynamic } from ‘@angular/platform-browser-dynamic’;<br>import { getTranslationProviders } from ‘./i18n-providers’;</p><p>import { AppModule } from ‘./app.module’;</p><p>getTranslationProviders().then(providers =&gt; {<br> const options = { providers };<br> platformBrowserDynamic().bootstrapModule(AppModule, options);<br>});<br>[/code]</p><p>Seems simple, no?</p><h4>No.</h4><p>I had two problems. First, we do not use SystemJS. Second, we were using the UpgradeAdapter to bootstrap an angular 1 + 2 hybrid app.</p><p>While all of Angular’s guides use SystemJS, angular-cli uses Webpack, and that was the tool chosen by us. So that getTranslationsWithSystemJS has to be rewritten as something that uses webpack, ending up with this:</p><p>[code lang=”javascript”]<br>function getTranslationFilesWithWebpack(locale: string) {<br> return System.import(‘./assets/locale/messages.’ + locale + ‘.xlf’)<br>}<br>[/code]</p><p>Not that bad, huh? But it also requires support by webpack, so in webpack.config.js I had to add a rule for handling <em>xlf</em> files:</p><p>[code lang=”javascript”]<br>function webpackConfig(options) {<br> return {<br> devtool: false,<br> resolve: {<br> extensions: [‘.ts’, ‘.js’]<br> },<br> context: __dirname,<br> entry: {<br> main: ‘./src/main’<br> },<br> output: {<br> path: ‘dist’,<br> filename: ‘[name].bundle.js’,<br> sourceMapFilename: ‘[name].map’,<br> chunkFilename: ‘[name].chunk.js’,<br> publicPath: ‘/static/teachers-site/dist/’<br> },<br> module: {<br> rules: [<br> /* html, css and ts rules removed for brevity */<br> {<br> test: /\.xlf/,<br> loader: ‘raw’<br> },<br> {<br> test: /\.json|\.map$/,<br> loader: ‘ignore-loader’<br> }<br> ]<br> }<br> };<br>}<br>module.exports = webpackConfig;<br>[/code]</p><p>There is one key component:</p><p>[code lang=”javascript”]<br>{<br> test: /\.xlf/,<br> loader: ‘raw’<br>},<br>[/code]</p><p>This rule tells webpack that any <em>xlf</em> files it encounters should be inserted as raw text. Using System.import(&#39;path...&#39; + filename) tells webpack to create a split-point for files in <em>path</em> and will allow them to be imported by demand as a promise. (This feature is new from Webpack 2.)</p><p>We end up with something like that in our <em>dist</em> directory:</p><ul><li><em>main.bundle.js </em>containing our website</li><li><em>n.chunk.js</em> where n starts from 0 and counts for each <em>xlf</em> we have.</li></ul><p>(Note: we should probably find a way to rename the chunks)</p><p>I had to do two more important but subtle changes:</p><p>First, I had to add publicPath: &quot;/static/teachers-site/dist&quot; to the output section. Without that, our webapp would have tried to load the chunks from <em>https://host/teachers-site/0.chunk.js</em>, and we would get a confusing 404 error page which would send the runtime environment screaming.</p><p>Second, I had to let webpack know how to handle other files it might find. Turns out that when webpack finds a System.import call it parses any project file that might be a possible resolution, including configurations, map, and other stuff.</p><h4>But how do you hybrid?</h4><p>When our project started our hybrid app code looked pretty much like this:</p><p>[code lang=”javascript”]<br>// THIS DIDN’T WORK!!!<br>// app.module.ts<br>import { NgModule, forwardRef } from ‘@angular/core’;<br>import { BrowserModule } from ‘@angular/platform-browser’;<br>import { UpgradeAdapter } from ‘@angular/upgrade’;<br>import { AppComponent } from ‘./app.component’;<br>import {SharedModule} from “./shared/shared.module”;</p><p>export const upgradeAdapter = new UpgradeAdapter(<br> forwardRef(() =&gt; AppModule ));</p><p>declare var angular: any;<br>angular<br> .module(‘rootModule’)<br> .directive(‘testAngularTwo’,<br> upgradeAdapter.downgradeNg2Component(AppComponent));</p><p>@NgModule({<br> imports: [BrowserModule, SharedModule],<br> declarations: [AppComponent],<br> bootstrap: [AppComponent]<br>})<br>export class AppModule{}</p><p>// main.ts<br>import ‘./polyfills.ts’;</p><p>import { upgradeAdapter } from ‘./app/app.module’;<br>declare var document: any;<br>upgradeAdapter.bootstrap(document, [‘rootModule’]);<br>[/code]</p><p>I just couldn’t figure out how to pass the translation providers to angular 2’s bootstrap function! I looked up the <a href="https://angular.io/docs/ts/latest/guide/upgrade.html">docs</a>, and to my great surprise they all talked some UpgradeModule stuff. Very confusing.</p><p>Turns out that in Angular 2.2.1 the upgrade mechanism was revised completely. Or at least its public API. So I upgraded to 2.2.1 and reimplemented the upgrade mechanism using the new guidelines:</p><p>[code lang=”javascript”]<br>// app.module.ts<br>import {NgModule} from “@angular/core”;<br>import {BrowserModule} from “@angular/platform-browser”;<br>import {AppComponent} from “./app.component”;<br>import {UpgradeModule} from “@angular/upgrade/src/aot/upgrade_module”;<br>import {downgradeComponent} from “@angular/upgrade/src/aot/downgrade_component”;</p><p>@NgModule({<br> imports: [<br> BrowserModule,<br> UpgradeModule,<br> ],<br> declarations: [AppComponent],<br> entryComponents: [AppComponent]<br>})<br>export class AppModule {<br> ngDoBootstrap() {}<br>}</p><p>declare var angular: any;<br>angular<br> .module(‘slateClient’)<br> .directive(‘testAngularTwo’, downgradeComponent({<br> component: AppComponent<br> }));</p><p>// main.ts<br>import “./polyfills.ts”;<br>import {AppModule} from “./app/app.module”;<br>import {getTranslationProviders} from “./i18n-providers”;<br>import {platformBrowserDynamic} from “@angular/platform-browser-dynamic”;<br>import {UpgradeModule} from “@angular/upgrade/src/aot/upgrade_module”;</p><p>declare var document: any;<br>declare var console: any;<br>getTranslationProviders().then(providers =&gt; {<br> const options = {providers};<br> return platformBrowserDynamic().bootstrapModule(AppModule, options);<br>})<br>.then(ref =&gt; {<br> const upgrade = ref.injector.get(UpgradeModule) as UpgradeModule;<br> upgrade.bootstrap(document.body, [‘slateClient’], {strictDi: true});<br>})<br>.catch(console.log.bind(console, “Bootstrap Failed: “))<br>[/code]</p><p>Ah-ha! Finally, it worked!</p><p>But what’s going on?</p><p>In <em>app.module.ts</em> I used UpgradeModule as one of my modules imports, and I also removed the bootstrap: [AppComponent] section. This last bit is important! Our app is actually being bootstrapped by Angular 2, calling Angular 1, which in turns uses Angular 2 components, so Angular 2 shouldn&#39;t bootstrap any component itself! Instead, we need to put our components in entryComponents instead.</p><p>In <em>main.ts</em> we just ask for the translation providers, then (chaining promises, see <a href="https://missingclosure.wordpress.com/2016/11/16/promises-and-observations/">my post</a> about promises) we bootstrap Angular 2 as usual. This bootstrap process returns a promise too, so we chain to it in order to bootstrap Angular 1 using the UpgradeModule we injected to our AppModule.</p><p>Finally, notice that .catch(console.log.bind(console, &quot;Bootstrap Failed: &quot;)) at the end of <em>main.ts</em>. This turned out to be extremely valuable as I tried to to understand why I can&#39;t get angular to run.</p><p>So, here it is! I hope you’ll find this useful, and let me know if you find an even better way to include translations.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6ffbed570b2b" width="1" height="1" alt=""><hr><p><a href="https://medium.com/luftzig/angular-2-and-translations-6ffbed570b2b">Angular 2 and Translations</a> was originally published in <a href="https://medium.com/luftzig">Luftzig</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Promises and Observations]]></title>
            <link>https://medium.com/luftzig/promises-and-observations-81ae001710fb?source=rss----98aa7d946278---4</link>
            <guid isPermaLink="false">https://medium.com/p/81ae001710fb</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[angularjs]]></category>
            <dc:creator><![CDATA[Yoav Luft]]></dc:creator>
            <pubDate>Wed, 16 Nov 2016 17:13:59 GMT</pubDate>
            <atom:updated>2017-09-16T08:24:48.097Z</atom:updated>
            <content:encoded><![CDATA[<p>As part of our transition to Angular 2 one of my team members had given a talk about Angular 2 basics and what’s new. He based his talk on a course by Mosh Hamadani, where he talked mostly on what had changed from Angular 1 to Angular 2.</p><p>One of the features of Angular 2 that he mentioned as new to use is the use of observables. This had raised the question “what good are they anyway?”. I tried to answer, but I realized I couldn’t do that without some thought, and without laying down some concepts.</p><h4>In the Beginning</h4><p>JavaScript, the language of the web, is highly concurrent. While the code is actually being run by a single thread (well, almost…<a href="#footnote1">[1]</a>), the languages event loop based architecture makes concurrency and asynchronous code a considerable problem.</p><p>For example, our website deals with teachers who use our products. Consider that we have a view that needs the list of students of the current teacher, so it might look like this:</p><p>[code lang=”javascript”]<br>function view(studentsService) {<br> …<br> var students = studentsService.getStudents()<br> …<br>}<br>[/code]</p><p>In days of old (pre JavaScript, that is), getStudents() might have been a blocking function, so our code would have had to wait until an HTTP request would have been made, answered, and of course, handle any exceptions.</p><p>But in JavaScript this means that the web page will freeze completely, not responding to any user action! So in the early days of JavaScript the solution that was found is to pass to getStudents() callbacks that will be handled later, for example:</p><p>[code lang=”javascript”]<br>studentsService.getStudents(<br> function onSuccess(result) {<br> students = result.students<br> }, function onFailure(error) {<br> panic()<br> })<br>[/code]</p><p>Our code became asynchronous, and when we get successful response our onSuccess function (usually called &quot;callback&quot;) is called with the result, and on failure our onFailure function will be called. Pretty basic stuff that every front-end developer is familiar with.</p><p>But let’s say for instance that our success callback needs to do something asynchronous too. Our code will then become something like</p><p>[code lang=”javascript”]<br>var students, result;<br>studentsService.getStudents(<br> function onSuccess(studentsResult) {<br> students = studentResult.students;<br> getClassesForStudents(<br> students,<br> function onClassesSuccess(classesResult) {<br> result = doSomethingsWith(students, classesResult)<br> },<br> function onClassesFailure() {<br> …<br> }),<br> function onStudentsFailure() {<br> …<br> })<br> [/code]</p><p>Not so elegant, isn’t it? Of course we could refactor it, but there are still some obvious problems, for example:</p><ul><li>Does getStudents() return a result? It is not obvious, and any changes it does are ought to be side-effects, a known evil.</li><li>Can I separate the code into several modules? If so, how?</li><li>Does every call need both onSuccess and onFailure? What if want to handle success one after the other but failures only once?</li><li>How do I follow the flow of control? What callback receives which data?</li><li>What happened to language constructs like return and throw?</li></ul><p>That’s where promises come.</p><h4>Promises</h4><p>We can notice a pattern in the callbacks example: we do something, then we get (at some point in the future) a result that can be either a success or failure, and we need to handle it. And then again, we might get either a success or failure and so on.</p><p>Promises encapsulate this pattern by defining a type that says “I’m either a result of type X or an error of type Err, but you’ll have to wait to find out.” This type also defines operations on it, in JavaScript ES6 they are called then and catch. While JavaScript isn&#39;t a strongly-typed language, I find that using type signatures makes it clearer:</p><p>[code]<br>Promise&lt;X, Err&gt; {<br> then : (successHandler: (X) =&gt; Y) =&gt; Promise&lt;Y, Err&gt;,<br> catch: (errorHandler: (Err) =&gt; Y) =&gt; Promise&lt;Y, Err&gt;<br>}<br>[/code]</p><p>(I’m using TypeScript’s type notations)</p><p>In laypeople terms: a Promise for type X and error Err has two methods: then which accepts a function that takes X and return Y, returning a new promise of type Y. And catch that does the same for errors.</p><p>What is the gain? First, our asynchronous functions now return a value. We can use this value to attach handlers that will process the result piece by piece. We can also pass the promise (original or the one returned from a then or catch call) to other places in our code that need to know nothing about our implementation! They only need to know that they will receive a Promise that will resolve to value, to which they can attach a then handler and do stuff with it, like assigning it to closure variables, handle an error, process the result or chain it some place else.</p><p>Simple, nice, and well encapsulated, and in our code:</p><p>[code lang=”javascript”]<br>var students;<br>var studentsPromise = studentsService.getStudents();<br>studentsPromise<br> .then(function (httpResult) {<br> return httpResult.students<br> })<br> .then(function(students){<br> return getStudentsWithClasses(students)<br> })<br> .then(function(resultStudents){<br> students = resultStudents // side-effect!<br> })<br> .catch(function(error) {<br> return handlerError(error)<br> })<br>[/code]</p><p>Notice that the catch in the end of the chain can gather all the errors that might have happened before reaching it. This is because promises have an amazing property that a failed promises handler will keep returning failed promises until someone catches the error and return a new, not failed value by returning a value from a catch handler. But notice, at all time we are dealing with promises! They encapsulate the state of our request and handle the transformation of the result.</p><p>And what happens when the code inside a handler throws an error? The promises abstraction says that the error will become a failed promise containing the error, for example:</p><p>[code lang=”javascript”]<br>studentsService.getStudents()<br> .then(function(httpResponse) {<br> throw Error(“No students!”)<br> })<br> .catch(function (error) {<br> console.log(error) // Print “No Students!”<br> })<br>[/code]</p><p>The use of return and throw statements are probably the biggest selling feature of promises. They give us back clean, functional code using language constructs we know and love.</p><p>Of courses, we could split the chain of promises anywhere we want. For example, taking our first example with promises, we can move the knowledge concerning the shape of the result to the getStudents method itself:</p><p>[code lang=”javascript”]<br>// StudentsService.js<br>/** getStudents<br> * returns: Promise&lt;Student[], HttpError&gt;<br> */<br>function getStudents() {<br> return http.get(‘/students’).then(function (response) {<br> return response.students<br> })<br>}</p><p>// ClassView.js<br>var students;<br>studentsService.getStudents()<br> .then(function(students){<br> return getStudentsWithClasses(students)<br> })<br> .then(function(resultStudents){<br> students = resultStudents // side-effect!<br> })<br> .catch(function(error) {<br> return handlerError(error)<br> })<br> [/code]</p><p>Now ClassView.js needs to know nothing about the response from the server. All it needs to know is that it will receive a promise that will contain an array of students, or some error message (specifically, HttpError).</p><p>(Actually, promises are monads, which is a large category of abstractions that have for our concerns this very same property of being transformed into other states of the monad while retaining important information and the same interface along the way. But that’s out of the scope of this discussion.)</p><p>For more insight and great examples of promises including how to handle multiple promises, see this <a href="https://pouchdb.com/2015/05/18/we-have-a-problem-with-promises.html">post</a> by Nolan Lawson</p><p>This seems pretty good, do we need something more?</p><h4>Observables</h4><p>Turns out that yes! We need more. Promises are cool, but have some limitations. One obvious limitation is that they handle a single event. This where Observables come in, but that’s in another post.</p><h4>Footnotes</h4><p>[1] WebWorkers, part of ES6 adds actual, multi-threaded concurrency to JavaScript.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=81ae001710fb" width="1" height="1" alt=""><hr><p><a href="https://medium.com/luftzig/promises-and-observations-81ae001710fb">Promises and Observations</a> was originally published in <a href="https://medium.com/luftzig">Luftzig</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Angular 1 to 2]]></title>
            <link>https://medium.com/luftzig/from-angular-1-to-2-17c590fd3b9?source=rss----98aa7d946278---4</link>
            <guid isPermaLink="false">https://medium.com/p/17c590fd3b9</guid>
            <category><![CDATA[angularjs]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Yoav Luft]]></dc:creator>
            <pubDate>Wed, 16 Nov 2016 16:47:19 GMT</pubDate>
            <atom:updated>2017-09-16T08:24:37.073Z</atom:updated>
            <content:encoded><![CDATA[<p>We had recently decided in Matific to rewrite large sections of our website. As with all projects, our website had some good code, some old code, some bad code and some “terrible oh the horrors!” code. Refactoring seemed like the right way to go forward, and with that we decided to move to Angular 2.</p><p>There were a number of reasons for making the transition. First, and foremost, our main website used an absolute version of Angular. Really, really old version, with really old bugs and vulnerabilities. Second, in the long run Angular 1 will disappear and eventually it wouldn’t be maintained anymore, so one must go with the time.</p><p>The choice in Angular 2 seemed the easiest, with the promise of gradual migrations. I’ll try in the following posts to document my insights from making the transition from Angular 1 to Angular 2, hoping that it will help some people trying to decide.</p><p>But first: On <a href="https://missingclosure.wordpress.com/2016/11/16/promises-and-observations/">promises and observations</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=17c590fd3b9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/luftzig/from-angular-1-to-2-17c590fd3b9">From Angular 1 to 2</a> was originally published in <a href="https://medium.com/luftzig">Luftzig</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[PyCon-IL 2016]]></title>
            <link>https://medium.com/luftzig/pycon-il-2016-2a559a096f1e?source=rss----98aa7d946278---4</link>
            <guid isPermaLink="false">https://medium.com/p/2a559a096f1e</guid>
            <dc:creator><![CDATA[Yoav Luft]]></dc:creator>
            <pubDate>Sun, 29 May 2016 07:57:44 GMT</pubDate>
            <atom:updated>2017-09-16T08:24:40.050Z</atom:updated>
            <content:encoded><![CDATA[<p>(This was intended to be a long post… sadly, most of it got deleted… so here a short version)</p><p>The first PyCon in Israel was held on 2–3 of May 2016 in Ramat Gan and was absolutely amazing. I didn’t plan on going in the first place (my employer asked us choose between going to PyCon or going to that yet to be announce AngularJS conference), but I’ve ended up going anyway, which is great!</p><p>First and for most, the conference was well organized, pleasant and fun! Kodos the team of volunteers who made that happen, and to the companies how gave their sponsorship.</p><p>Second, compared to the two other industry conventions I’ve attended (Jenkins and Codemotion TLV), PyCon felt younger and more diverse. I would throw a guess and say that about 30% on the conference crowd were women — still a low percent, but considerably higher than the other aforementioned conferences. This is good step forward!</p><p>Third and not least, the talks were great. As always, some were greater than others, and being a two-track conference I’ve only attended about half of them, but those I had seen were really good. Although, I think some of them would have been better if they were a 45 minutes talk rather than a 30 minutes one, but what the hack.</p><h4>Highlights</h4><ul><li>Rony Sheer talked about teaching programming to high school students through projects.</li><li>Ola et Ola from Django Girls gave an inspiring talk about the project.</li><li>“Practical Metaclasses” by Zack Sims was pretty interesting, and most important, practical!</li><li>Raymond Hettinger’s keynote about design reviews is a must. While being very entertaining he had some important notes on how to review an idea and design and avoiding hyper-generalized or under-generalized solutions.</li><li>Jonathan Schemoul’s talk about IoT device programming in Python is one that I should review. It seemed very intriguing, but I couldn’t follow it fully.</li></ul><h4>Summary</h4><p>PyCon was great, and looking through the list of talks I’ve noticed that there were a few promising talks that I missed entirely. Almost all of the talks I attended were very good relevant, and the organization was smooth. I’m looking forward for next year’s PyCon!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2a559a096f1e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/luftzig/pycon-il-2016-2a559a096f1e">PyCon-IL 2016</a> was originally published in <a href="https://medium.com/luftzig">Luftzig</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>