<?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 Thiago Araújo Silva on Medium]]></title>
        <description><![CDATA[Stories by Thiago Araújo Silva on Medium]]></description>
        <link>https://medium.com/@thiagoaraujos?source=rss-84180f96c985------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ZpoOOPMtqwm7KRdLPj5Png.jpeg</url>
            <title>Stories by Thiago Araújo Silva on Medium</title>
            <link>https://medium.com/@thiagoaraujos?source=rss-84180f96c985------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 08:51:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@thiagoaraujos/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[On Writing a Great Pull Request]]></title>
            <link>https://medium.com/codeminer-42/on-writing-a-great-pull-request-37c60ce6f31d?source=rss-84180f96c985------2</link>
            <guid isPermaLink="false">https://medium.com/p/37c60ce6f31d</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[pull-request]]></category>
            <category><![CDATA[writing-tips]]></category>
            <dc:creator><![CDATA[Thiago Araújo Silva]]></dc:creator>
            <pubDate>Tue, 06 Mar 2018 20:39:33 GMT</pubDate>
            <atom:updated>2018-11-08T16:30:38.152Z</atom:updated>
            <content:encoded><![CDATA[<h4>Getting into the mindset of efficient pull requests</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*awcJ9IT-opcktKBidcFREw.jpeg" /></figure><p>Nowadays, pull requests are essential tools to enable seamless collaboration within software teams. They’ve changed our workflows for the better and became a standard development practice.</p><p>Although there are many useful guides on the internet about increasing the quality of pull requests, this post aims to provide my own take on the matter: what I think are the essential characteristics of a great pull request. The focus will be on the pull request itself, not on the accompanying code. I shall note that this is my personal opinion, and some points may not apply to your case.</p><h3>Don’t make me think</h3><p>Bob is opening a pull request for something he’s been working on over the past few weeks. It’s a complex feature that touches legacy parts of an old codebase, and the changeset is comprised of 50 files. A huge mix of red and green can be seen in the diff. He writes the following title:</p><pre>Implement IDK integration</pre><p>And along with it, the following description:</p><pre>Reference: <a href="http://github.com/cool_project/issues/666">http://github.com/cool_project/issues/666</a></pre><p>Lastly, he clicks on “Create Pull Request”. That’s great, now he can relax and move on to the next thing!</p><p>Joe has been assigned to review Bob’s pull request. Of course, the title is the first element to stand out: “Implement IDK integration”. But then he asks, “what’s IDK?” The description doesn’t mention what IDK is. “OK, let me Google up”. He clicks on the first result, but it does not seem to be useful. He then heads to the next result. After a few random tries, he figures out what IDK is and what it’s used for.</p><p>Joe flips back to the pull request and a link to the issue calls his attention. “Let’s see what we’ve got in there”. Even though the issue’s description seems utterly confusing, he tries to fish something interesting out of it. He scrolls through a long thread of comments. The tenth comment is very lengthy and introduces new details, also changing the state of what’s been written in the main description. As if that was not enough, most comments force Joe to keep track of newfound details, making up a not-so-funny jigsaw puzzle.</p><p>After wasting yet more time, Joe acknowledges the different parts of the feature and the business goals. However, it’s a considerable amount of context to keep in his head at once, so he may even refer to the issue again in case he forgets something.</p><p>With that out of the way, Joe can finally start reviewing the code. He clicks on the “Files changed” tab, and unsurprisingly, he can barely understand <em>what’s </em>been changed in the first file, and how that change relates to the next file, or any other file for the matter. Joe spends 1 hour, perplexed, looking at the code, bouncing back and forth, but he still doesn’t know what to do. Bob isn’t online or even available for Joe to ask questions.</p><p>Joe finally figures out what the <em>entry point</em> of the code is, and what files he should look up next! He checkouts Bob’s branch on his computer and starts playing with the code. He spots a code change that seems absurd, and leaves a comment with questions. Actually, one among many!</p><p>Hours go by, and Joe stumbles across something that invalidates his first comment, but at this point it’s just a supposition. Time passes, and Joe’s supposition is suddenly confirmed. He finally gets it: Bob was working around a pressing issue of the legacy codebase. Now it makes total sense!</p><p>Joe has time boxed his review because he’s a busy fella and has other things to do. He finishes his review and submits it. On the next day, Bob replies to Joe’s comments, and <em>some</em> of his answers explain why the code looks and behaves a certain way. After a few rounds of code review, the reasons behind key parts of Bob’s design suddenly become clear. But at this point it might be too late to suggest design changes.</p><h3>What’s the problem?</h3><p>It’s inevitable. If a pull request is not descriptive, people will be lazy or not willing to spend much time on it. They’ll probably comment on some specific technicality or syntax detail, and pretend to have submitted a meaningful review. Or they will complain and ask for more details. Or they will simply think : ”I’m the worst code reviewer in the world. How can I not understand this? Others get it so much faster than me!” — and that’s not what’s actually going on.</p><p>This is not good at all. Neither for the reviewer, nor the company, nor the project, not even you! Code may be merged with bugs and the design may slowly hinder future development around it. And worse yet, the code may be solving the wrong problem, but there’s a chance nobody noticed this fact.</p><p>Everyone commits such mistakes, and that’s exactly what a code review is for: gathering people with diverse backgrounds and prying eyes to improve the overall quality of the work.</p><h3>The most important ability of a developer: putting oneself in the shoes of others</h3><p>Bob is the person working on the IDK feature. He’s gone through all the trouble of understanding what IDK is, what the issue is about, what the business goals are, the perils and pitfalls of the legacy codebase, what parts of the code are relevant, the approach to implementing it, and so forth. The devil is precisely in these details.</p><p>But each reviewer has to go through the same path as Bob, over and over again — especially if they are not familiar with the feature or important aspects around the feature. Which means the reviewer’s time is not being respected. What could have Bob done instead?</p><h3>Clear out the path</h3><p>The perfect pull request clears out the path for reviewers <em>as much as possible</em>. Imagine you are the reviewer. How would you go about understanding your own pull request?</p><h3>Explain the issue</h3><p><em>Sometimes</em>, just providing a link to the issue is not enough. The problem is that issue threads are chronological and often full of noise, therefore important information may be scattered or just plain inaccessible.</p><p>A great attitude is to explain the issue in the context of your changes. Whoever wrote the issue has a certain point of view about the matter, and you are in charge of materializing that view into code. More than anyone, you hold a lot of hands-on knowledge that could be transmitted along with your code.</p><p>Explain in a few sentences or paragraphs what you are dealing with, and provide relevant links in case the reviewer wants to go deeper. In the IDK example, it could be explained what IDK is, what the goals of integrating IDK into the application are, the touchpoints, and so on.</p><blockquote>Explain what the feature is and why it’s being done</blockquote><p>And also, provide a link to the issue along with the text. Best case scenario is when your explanation avoids a click to that link, but keep in mind that’s not always possible or feasible.</p><h3>Provide context</h3><p>Now we’re on the technical side of the force. What prerequisites does the reviewer need in order to delve into the problem you are solving? What can you show to the reviewer to make things easier to understand? Can you write a text? Can you provide a directory listing with the tree command? Would that help? <em>What</em> would help?</p><h3>Provide a starting point and a path</h3><p>Is there an entry point from where logic branches off? In web applications that’s usually the controller or a spot where a top-level component is instantiated — or something else entirely different. Just don’t assume it is obvious! You may even have a multitude of controllers, but in that case you should elect the most important ones.</p><p>After writing down these entry points, you <em>may</em> suggest a script for the reviewer to follow. In GitHub pull requests, you can’t reorder changed files manually, but you can write that information down in the description.</p><h3>Provide visual resources</h3><p>If you are doing frontend work, your PR can likely benefit from an annotated screenshot, a gif, or a video that represents the outcome of your work.</p><p>In other cases, you can resort to resources such as diagrams. For example, for showing how modules, components, or services interact between each other. Whether you choose to provide these or not, it’s up to your judgement!</p><h3>Explain the code</h3><p>Code is made of expressions, functions, classes, modules, files, namespaces, and so forth. Understanding a function, depending on how it’s written, may be easy enough. The real challenge is understanding how things are put together and <em>how they provide</em> <em>value</em>. And it’s likely that your reviewer is struggling exactly with that.</p><p>No matter how “clean” your code may appear to be, it’s a sea of information that people will try to make sense of. Therefore, take an extra leap and explain in a few sentences or paragraphs what your code does. People will thank you for that!</p><blockquote>Take an extra leap and explain in a few sentences what your code does</blockquote><h3>Explain the design</h3><p>Coding is a complex activity, and there are many ways to put a feature together — each with different tradeoff characteristics. Some decisions are not easy to make, but we have to make them all the time, right? That’s what we’re good at. And it boils down to design: finding out the best structure — whether existing or not — to accommodate code changes, taking into account the current state of affairs.</p><p>Never assume your design is obvious. There may be subtly interconnected parts making it up, and if you don’t explain it bluntly, people will take longer than necessary to understand your intents. So write about <em>how</em> you approached the problem. It will be much easier for anyone to chime in and suggest improvements.</p><blockquote>Write about <em>how</em> you approached the problem</blockquote><p>Simpler is better, but if you resort to a well-known approach or design pattern, make sure to spell it out in detail. That’s ubiquitous language familiar to developers, so use that to your advantage!</p><h3>Comment along the PR</h3><p>What if you have something <em>specific</em> to comment that relates to a certain part of the code but does not fit into the main description? For example, it would not help saying <em>“In the function X of module Y, I did Z and W”</em>. After all, the reviewer is still reading the description, so he may not have looked at the code yet.</p><p>That’s why you should review your own PR — usually more than once — and comment on any puzzling parts that would be better understood with the help of human language. Empty your cup before looking at your code and you will have a clue on what to explain and how to explain whatever it is you need to explain.</p><blockquote>Always assume your description can be understood without looking at any code</blockquote><h3>Refer to historical information</h3><p>Code has an implicit history that’s written throughout commits, issues, and other artifacts. And it’s likely that you had to look up these resources while seeking the best approach to deal with key parts of the code. That’s even more likely if your changes are broad or deep.</p><p>In that case, you may provide links to past issues, commits, pull requests, and briefly explain what they have to do with your changes.</p><p>Even if you haven’t done any research, it might be useful to explain in general terms how the pre-existing code plays out in your changes. You may also have to explain about code that’s <strong>not</strong> part of the diff, but has an implicit influence on your work.</p><h3>Should it always be like that?</h3><p>Absolutely not! The best possible situation is when you write the bare minimum that does not omit essential information. That’s exactly the challenge. If your description is very lengthy or elongated, it will discourage people from reading it.</p><p>When your pull request is simple — say a superficial change or bug fix — you can probably get by with just the issue’s link. And remember: you can’t explain <em>everything</em>. <strong>You shouldn’t</strong>. The goal is to enable easy discovery and allow your reviewer to focus on what’s important.</p><p>So, try to be concise and objective. Make sure your text has a nice progression and rhythm. Make sure the key elements to understanding your work are explicitly stated. Cut down on unnecessary words and sentences. Divide up sections logically. Think of the other person and be a sensible developer.</p><p>By doing that, you — the expert — is saving everyone’s time. Let’s say you can compose your pull request in 1 hour and save 4 hours per reviewer. That’s a big win for everyone!</p><h3>Now make me think</h3><p>Given that you’ve cleared out the path for reviewers, you can now focus on asking the questions that you consider to be important — in other words, what you are craving for feedback. List your requests explicitly in the description or via comments.</p><p>Keep in mind you are just facilitating the reviewer’s jobs as much you can. That does not mean the reviewer should not think outside of the box!</p><p>In any case, good reviews take time. But if you make it easier and smoother, they will take <em>far less</em> time, and the overall quality of the work will be better in the end. Thus, your pull request will reach peak efficiency — just as it ought to be!</p><p>I would love to hear what you think. If you have any comments or experiences, please leave it up below. Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37c60ce6f31d" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeminer-42/on-writing-a-great-pull-request-37c60ce6f31d">On Writing a Great Pull Request</a> was originally published in <a href="https://medium.com/codeminer-42">The Miners</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Functional Object Composition and MVC]]></title>
            <link>https://medium.com/codeminer-42/functional-object-composition-and-mvc-d914144e923f?source=rss-84180f96c985------2</link>
            <guid isPermaLink="false">https://medium.com/p/d914144e923f</guid>
            <category><![CDATA[object-oriented-design]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[object-oriented]]></category>
            <category><![CDATA[mvc]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Thiago Araújo Silva]]></dc:creator>
            <pubDate>Mon, 01 May 2017 23:15:20 GMT</pubDate>
            <atom:updated>2017-05-05T13:02:17.167Z</atom:updated>
            <content:encoded><![CDATA[<h4>Gluing together encapsulation and functional programming</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O-4lat-uRPOHHissNZVx7w.jpeg" /><figcaption>This is not just a fragile hack, it’s a powerful glue!</figcaption></figure><p>I just read a <a href="http://www.yegor256.com/2016/12/13/mvc-vs-oop.html">great blog post</a> on the internet about MVC not being object-oriented, and I could not agree more — after all, we don’t peel an apple the same way do with a banana. However, heads up: I am not an OOP <em>purist</em>, and I believe procedural programming has its place among apps written in that paradigm.</p><p>The author of the referred to post suggests <em>object composition</em> as an alternative to replacing MVC layers. In his words, MVC takes the opposite direction of OOP: it exposes the data and hides behavior, while the latter hides the data and exposes behavior. The controller is in charge and fetches naked data from the model, makes assumptions about it, and injects the result into the view. A single object does not retain knowledge about the data, which means there is no <strong>encapsulation</strong>, and therefore no OOP. ☑</p><p>It gets even worse when doing MVC by the book. Classic MVC apps are comprised of only controllers, models, and views. Hence each and every responsibility gets distributed <em>somehow</em> among these layers. This convention is not <em>necessarily</em> wrong: it empowers beginners to get off the ground quickly and allows them to figure out in a snap where logic goes. It is good for prototyping and bad for <em>mostly</em> everything else — unless we make a conscious effort to spreading out the M layer across smaller objects.</p><p>Now I ask: is it possible to use MVC while still leveraging OOP benefits? The answer is <strong>yes</strong>. To be honest, I don’t care if MVC is OOP or not, because it <em>can</em> as well behave as the delivery mechanism for such apps; I mostly care if the code is reusable <em>when it needs to be</em>.</p><p>As long as we reach the same maintainability benefits that we aim for by means of these abstractions, there is no reason to go nuts! In other words, I’d certainly worry about dodging away from MVC in a framework that adopts it as the default delivery mechanism, though I would not give up on OOP!</p><p>This partially theoretical post explores the following topics:</p><ul><li>Using OOP in an MVC app while gleaning encapsulation benefits.</li><li>Going further and using object composition instead of MVC. How would it be? Where to use it?</li><li>Imagining object composition as a first class feature of OO languages.</li></ul><h3>Making it more OOP</h3><p>Let’s start with an MVC example written in Rails which we’re all familiar with:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ce40f1848e2966a614de1cdae80322c7/href">https://medium.com/media/ce40f1848e2966a614de1cdae80322c7/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/190732a0d1a085e8055a76b744eb53fe/href">https://medium.com/media/190732a0d1a085e8055a76b744eb53fe/href</a></iframe><p>The following points are worth making clear:</p><ul><li>We can’t easily reuse the controller.</li><li>The @books collection holds Book instances which are used in the view layer. We access their attributes directly there, and <em>sometimes (sic) even in the controller.</em></li><li>We can still reuse the model independently.</li><li>We can reuse the view regardless.</li></ul><p>Clearly, our biggest concern pertains to the controller: it is highly coupled to the router and sometimes to the views, especially in a framework like Rails. However, we can move its logic to another class:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/74a6ec96db93484f2fa8b342ab2e9940/href">https://medium.com/media/74a6ec96db93484f2fa8b342ab2e9940/href</a></iframe><p>And call it like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3318d980c93a7d77906ad48668c5d51e/href">https://medium.com/media/3318d980c93a7d77906ad48668c5d51e/href</a></iframe><p>So far so good. Now let’s suppose we need an endpoint to filter books by gender and other attributes – it’s essentially the same logic with new functionality added on top. Our requirements demand this to be a distinct resource:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5caa9301eb0f721b7128d8097f415afc/href">https://medium.com/media/5caa9301eb0f721b7128d8097f415afc/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3d5d03af02fc594cdc2b7fe515b3f41/href">https://medium.com/media/c3d5d03af02fc594cdc2b7fe515b3f41/href</a></iframe><p>Although our new controller shares most of its purpose with BooksController (while still being different), we still had to write it! Nonetheless, this is attenuated by the fact that our code became DRY due to both controllers sharing common logic. Also, we went a great way toward making it more object-oriented:</p><ul><li>BooksList retains knowledge of how to fetch a books list.</li><li>BooksFilter knows how to filter books.</li><li>We are <strong>composing</strong> these two objects together.</li><li>We added a BookView object to clean up the template, and it uses object-oriented helpers: imagine Sentence implementing to_s and to_str methods.</li><li>We removed procedural logic from the view.</li><li>Neither the controller nor the view knows about the innards of a book data structure. This is taken care of by BookView.</li></ul><p>Now, that’s object-oriented programming!</p><p>Still, the controller and the view are not object-oriented, but I’m OK with this: the view is reusable and it counts with a presenter layer, and we moved our controller’s logic to another object.</p><h3>Refactoring to object composition</h3><p>The controller is a piece of boilerplate that we need to write every time, and it’s the default mechanism by which we hook into the views. Can we improve our situation if we make the VC part of our code more object-oriented?</p><p>Let’s envision what we have so far closer to what <a href="http://www.yegor256.com/2016/12/13/mvc-vs-oop.html">the article</a> suggests, starting off from the router:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/57611d0bb70690c6c0a2dcb6a15842df/href">https://medium.com/media/57611d0bb70690c6c0a2dcb6a15842df/href</a></iframe><p>I like this version! Controllers are gone and have been transformed into flexible objects. If you are wondering about PrintedBooks, let’s imagine it being something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/366fbee2d21804a99fb3cbedbf1c6c42/href">https://medium.com/media/366fbee2d21804a99fb3cbedbf1c6c42/href</a></iframe><p>PrintedBooks is playing the role of the controller, except that it’s now <em>composable</em> and it knows what to do with its data, so we just tell it: printed_books.call.</p><p>What’s unusual about this approach is that we see at a glance everything the action does— all steps are utterly explicit, and they communicate us at a high level how the code works. Also, we are calling our renderer inside PrintedBooks, and that may be a good thing: we finally know where the rendering functionality comes from!</p><p>Furthermore, it’s obvious where to put new functionality, and we are not worrying about categorizing objects as controllers, models, views, presenters, services, etc.— which can be liberating! Some clever namespacing would likely lend more shape to our code and make it a breeze to maintain while revealing the domain more clearly (Library::PrintedBooks is cool, don’t you think?).</p><p>Finally, one aspect sprung out after shifting our mindset to object composition: <strong>we are working with an object pipeline</strong>! And that reminds me of functional programming.</p><h3>Object composition as a first class citizen</h3><p>What if Ruby had a pipe operator akin to Elixir’s to <em>compose objects</em>? It would preserve its data encapsulation characteristics and still incorporate functional programming concepts such as first-class functions.</p><p>That feature would be even better alongside some sort of enforced object immutability, for example, “only assign instance variables at the constructor.”</p><p>Let’s picture an imaginary version of Ruby:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f770f75116c6b6c16276cc1425adb093/href">https://medium.com/media/f770f75116c6b6c16276cc1425adb093/href</a></iframe><p>Although equivalent, it reads much better than our pure-Ruby example. If you’ve heard about Elixir’s pipe operator, I bet this code makes you feel at home!</p><p>While we should go from the inside-out in our former example to understand the flow, here we take the opposite direction and pass the result of the current expression as the first parameter of the expression that follows until getting the final object. <a href="https://elixirschool.com/lessons/basics/pipe-operator/">This page</a> explains the idea in more detail.</p><p>I’m sure such a feature would encourage us to compose objects and functions more frequently, and it would change the way we think about object-oriented programming.</p><h3>OK, where can I use this?</h3><p>I’m not aware of any language that implements “first class object composition”, but you can apply our MVC-equivalent code <em>today</em> in Ruby frameworks like <a href="https://github.com/sinatra/sinatra">Sinatra</a> and <a href="https://github.com/jeremyevans/roda">Roda</a>. With these tools, you are free to roll your own app however you want (if you know what you’re doing!). For instance, this could very well be a Sinatra application:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca79fa469f44d9e9cceb1bc5fb4fa549/href">https://medium.com/media/ca79fa469f44d9e9cceb1bc5fb4fa549/href</a></iframe><p>As for Rails applications, you can still enjoy object composition in non-MVC parts — but you have to obey some conventions if you want to succeed.</p><p>Finally, it’s important to say: don’t allow convoluted logic to spread inside router blocks! This attitude forces you to keep things clean and figure out exactly which objects you need in your pipeline and how they fit together.</p><h3>Conclusion</h3><p>I dig object composition, and we can extend this line of thinking beyond MVC. If you’ve worked with functional programming before, you certainly know how flexible function composition can be, and the same may apply to objects which retain control of their data.</p><p>I don’t think there exists a <em>winner</em> between OOP and FP; they are different beasts. Each paradigm offers a way of thinking and reasoning about programs, regardless of flaws they may have developed over time. But we can certainly have FP concepts applied to OOP for the win. And why not, apply OOP concepts to FP for the win!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d914144e923f" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeminer-42/functional-object-composition-and-mvc-d914144e923f">Functional Object Composition and MVC</a> was originally published in <a href="https://medium.com/codeminer-42">The Miners</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to Test Shared Behavior in Elixir]]></title>
            <link>https://medium.com/codeminer-42/how-to-test-shared-behavior-in-elixir-3ea3ebb92b64?source=rss-84180f96c985------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ea3ebb92b64</guid>
            <category><![CDATA[elixir]]></category>
            <category><![CDATA[metaprogramming]]></category>
            <category><![CDATA[functional-programming]]></category>
            <dc:creator><![CDATA[Thiago Araújo Silva]]></dc:creator>
            <pubDate>Wed, 29 Mar 2017 18:16:03 GMT</pubDate>
            <atom:updated>2017-05-16T13:50:53.137Z</atom:updated>
            <content:encoded><![CDATA[<h4>Implementing functionality similar to RSpec’s shared examples</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*n-j3T1gfjD-EmsHyWUWTTw.jpeg" /></figure><p>Create a new mix project if you want to follow along:</p><pre>$ mix new calculator<br>$ cd calculator</pre><p>Suppose you have a Calculator module and a sum_list function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae7b6237294b258fbd82a56e7cc2d9b5/href">https://medium.com/media/ae7b6237294b258fbd82a56e7cc2d9b5/href</a></iframe><p>That’s straightforward enough. You can also write the reduce line more verbosely if you want:</p><pre>list |&gt; Enum.reduce(0, fn x, y -&gt; x + y end)</pre><p>And follows a test case to exercise the above functionality (not accounting for edge cases):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/97497f473bab80c478ba26ce93cc95cf/href">https://medium.com/media/97497f473bab80c478ba26ce93cc95cf/href</a></iframe><p>As you might expect, it passes successfully:</p><pre>$ mix test</pre><pre>.</pre><pre>Finished in 0.02 seconds<br>1 test, 0 failures</pre><p>Now here’s the picture: you are training your Elixir skills and you want to implement an alternative version of the code without deleting what you already have, and using the same tests as guides.</p><p>Also, you want to stick to the default <em>ExUnit</em> testing framework and avoid using a library like <a href="https://github.com/antonmi/espec"><em>ESpec</em></a> just to obtain this feature. How might you do that? Copy, paste and modify the test? <strong>No</strong>.</p><p>Let’s figure out a way to share tests between two or more modules.</p><h3>Passing arguments</h3><p>The first step in that direction is to pass the <em>module</em> that we want exercised as an argument to the test. If you are not aware, modules are represented by <a href="http://elixir-lang.org/getting-started/basic-types.html#atoms">atoms</a> in Elixir, which means they can be freely passed around like any other ordinary value.</p><p>Fortunately, <em>ExUnit</em> provides that feature out of the box. Here is the refactored test:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/32d15e74e51385cc53eb70b9fa48f4b1/href">https://medium.com/media/32d15e74e51385cc53eb70b9fa48f4b1/href</a></iframe><p>Allow me to explain: @moduletag is a <a href="http://elixir-lang.org/getting-started/module-attributes.html">module attribute</a>, and module attributes are evaluated at compile-time. The test macro is able to “capture” this value and pass it to the real test function, which is dynamically defined under the hood by the same macro. How exactly that happens is beyond the scope of this post, so just trust <em>ExUnit</em> and assume that it does the right thing.</p><p>As you can see, we are passing a <a href="http://elixir-lang.org/getting-started/keywords-and-maps.html#keyword-lists">keyword list</a> to the @moduletag attribute:</p><pre>@moduletag calculator: Calculator</pre><p>Which is the same as doing this:</p><pre>@moduletag [calculator: Calculator]</pre><blockquote>In a similar vein to its Ruby cousin, we can omit brackets in Elixir when doing method calls</blockquote><p>That <a href="http://elixir-lang.org/getting-started/keywords-and-maps.html#keyword-lists">keyword list</a> goes all the way down to the test method and we can <a href="http://elixir-lang.org/getting-started/pattern-matching.html">pattern match</a> against a map to extract what we want: calculator. <em>ExUnit</em> compiles all tags down to a map, therefore we don’t pattern match against a keyword list.</p><p>After this step, everything should work just as before:</p><pre>$ mix test</pre><pre>.</pre><pre>Finished in 0.02 seconds<br>1 test, 0 failures</pre><blockquote><strong>NOTE</strong>: <em>@moduletag</em> options are passed to <strong>all</strong> <strong>tests</strong> of a module. You can also pass individual options to each test using the <em>@tag</em> attribute</blockquote><h3>Sharing the tests</h3><p>Now that we gleaned what we need from <em>ExUnit</em>, let’s start sharing our examples! One way to accomplish that is by extracting our tests into a separate module and <a href="http://elixir-lang.org/getting-started/alias-require-and-import.html#use"><em>using</em></a> the module where we want; in this way, we can customize options passed to each one:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c837568b27ef375dd0588f78fd8ad779/href">https://medium.com/media/c837568b27ef375dd0588f78fd8ad779/href</a></iframe><p>To leverage the <a href="http://elixir-lang.org/getting-started/alias-require-and-import.html#use">use</a> feature, let’s define a __using__/1 macro to return the AST of the code that we want evaluated in each target module during compile-time. It goes like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/60cda7135b985be263b06c3c2cba69ca/href">https://medium.com/media/60cda7135b985be263b06c3c2cba69ca/href</a></iframe><p>What did we just do? Correct, we just transferred logic from CalculatorTest to __using__/1. Moreover, the code gets transformed into an AST by the quote/1 function.</p><blockquote>It’s code that generates code</blockquote><p>As for the options argument, it <em>already</em> enters the macro as an AST, so we just unquote it to mix up its instructions into the final AST:</p><pre>@moduletag unquote(options)</pre><p>Had we not used unquote, the compiler would have assumed options is a function call associated with the runtime, and it would all blow up!</p><p>Back to our tests, everything should still be good if we re-run them:</p><pre>$ mix test</pre><pre>1) test sums a list of values (AltCalculatorTest)<br>     test/calculator_test.exs:28<br>     ** (UndefinedFunctionError) function AltCalculator.sum_list/1 is undefined (module AltCalculator is not available)</pre><pre>.</pre><pre>Finished in 0.05 seconds<br>2 tests, 1 failure</pre><p><em>Ops</em>, we have one success and <strong><em>one failure</em></strong><em>, </em>but that’s exactly what we want!</p><p>It just means CalculatorTest works the same, while our new module (AltCalculator) still has to be implemented. The good news is that we can use exactly the same tests to guide us on our way home.</p><h3>Polishing up</h3><p>I’m still not <em>happy</em> with that code. What if we need another set of shared examples? There will be lots of boilerplate to repeat, such as __using__/1, quote/1, unquote/1, etc. How can we make it more DRY?</p><p>Let’s picture <em>how</em> our functionality ought to be used. How about this?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3bdc0bfdbc4d8f50927f0035f068c00/href">https://medium.com/media/f3bdc0bfdbc4d8f50927f0035f068c00/href</a></iframe><p>This would be the easiest-to-read implementation I can think of, so let’s make it real!</p><p>First of all, we must define a SharedTestCase module with a define_tests/1 macro. Here’s the skeleton:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43a7fd4c01b074222e357614e0b73729/href">https://medium.com/media/43a7fd4c01b074222e357614e0b73729/href</a></iframe><p>Now we need to fill in define_tests/1 with the quoted definition of a __using__/1 macro in order to reach our final goal:</p><pre>use CalculatorSharedTests, calculator: Calculator</pre><p>Or to put it another way, we need a macro defining another macro! I know, this is <em>mind-bending</em>, but let’s proceed:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9e3146cc8870e29ae28d63d049758cf/href">https://medium.com/media/d9e3146cc8870e29ae28d63d049758cf/href</a></iframe><p>And that’s it! Take some time to read and analyze the code.</p><p>I won’t explain it thoroughly, but the reason why we are using <a href="https://hexdocs.pm/elixir/1.2.6/Macro.html#escape/2">Macro.escape/2</a> is because we are under two levels of quoting, and the block needs to be made available down at the second level. The first level wraps our original AST into code that can be used further down:</p><pre># Macro.escape &quot;escapes&quot; any <strong>value</strong> into an AST<br>block = unquote(Macro.escape(block))</pre><p>This is possible because ASTs are represented as tuples in Elixir. When the compiler does the <em>first</em> pass, it understands there’s a second quoting level and the code gets transformed into something like this:</p><pre># Yeah, this ends up unquoting an &quot;AST of an AST&quot; to get<br># back just an AST.<br>block = unquote(AST_OF_AST_TUPLE)</pre><p>When the compiler does the <em>second</em> pass (after injecting and actually evaluating the __using__ macro), unquote unwraps the value back into the original AST, which is exactly what we want.</p><p>If our line had been just unquote(block), the compiler would have looked for a “<em>block</em>” variable and there would have been errors. Instead, we are inserting our literal AST tuple into the template as a “local variable”.</p><blockquote><strong>NOTE</strong>: We can’t use the pipe operator in this specific situation: block = block |&gt; Macro.escape |&gt; unquote. To understand why, imagine that our code expands like the following ERB template: block = unquote(&lt;%= Macro.escape(block) %&gt;). Using the pipe macro would confuse the context and force the compiler to evaluate the line differently.</blockquote><p>And what is that do: block argument doing in define_tests? Turns out we are <a href="http://elixir-lang.org/getting-started/pattern-matching.html">pattern matching</a> against a <a href="http://elixir-lang.org/getting-started/keywords-and-maps.html#keyword-lists">keyword list</a> to extract our &quot;block”. In Elixir, there are no “blocks” such as in Ruby, instead they are pure syntactic sugar for <a href="http://elixir-lang.org/getting-started/keywords-and-maps.html#keyword-lists">keyword lists</a>. This code here:</p><pre>some_macro do<br>  1 + 1 = 2<br>end</pre><p>Is exactly the same as this one:</p><pre>some_macro([do: 1 + 1 = 2])</pre><p>Instead of being evaluated right away, the value 1 + 1 = 2 enters through the macro as an AST like the following:</p><pre>{:=, [line: 11], [{:+, [line: 11], [1, 1]}, 3]}</pre><p>When you see do..end in Elixir code, rest assured it is a macro. Even def, which we use to define methods, is a macro itself!</p><h3>The final code</h3><p>And here is the final code in all of its glory:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/61b53e72eca0b76b06a8a9f62d01f330/href">https://medium.com/media/61b53e72eca0b76b06a8a9f62d01f330/href</a></iframe><p>There may be a lot to digest, especially if you are not familiar with the language. Our final product is as clean to read as good’n’old Ruby code.</p><p>As a plus, you can also extend each test module with specific examples in addition to the shared ones! And remember, you still have a failing test to make pass!</p><h3>Conclusion</h3><p>This code can be reused in other Elixir projects: you can pass any parameters and customize shared tests to your liking, much like RSpec’s <em>shared examples</em>. That said, it may not be as full-featured as the latter.</p><p>The point herein wasn’t to explain all aspects of the code, otherwise it would get very lengthy and tiring in no time. If you want to learn more about metaprogramming, take a look at this <a href="http://elixirschool.com/lessons/advanced/metaprogramming/">awesome link</a>.</p><p>I hope this post encourages you to explore Elixir’s features further, just like I am doing. If you know about any libraries or alternative methods to implement this, please share it in the comments.</p><p><em>Happy TDD’ing!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ea3ebb92b64" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeminer-42/how-to-test-shared-behavior-in-elixir-3ea3ebb92b64">How to Test Shared Behavior in Elixir</a> was originally published in <a href="https://medium.com/codeminer-42">The Miners</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Refactoring Ruby: From Subclass to Registry]]></title>
            <link>https://medium.com/codeminer-42/refactoring-ruby-from-subclass-to-registry-b6fe4db58b18?source=rss-84180f96c985------2</link>
            <guid isPermaLink="false">https://medium.com/p/b6fe4db58b18</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Thiago Araújo Silva]]></dc:creator>
            <pubDate>Thu, 23 Mar 2017 13:16:08 GMT</pubDate>
            <atom:updated>2017-03-28T15:00:02.889Z</atom:updated>
            <content:encoded><![CDATA[<h4>From developing a solution to gradually improving it by listening to the pain</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*-ob3gfX2n3v36X8ri27buQ.jpeg" /></figure><p>My team was given a particularly laborious task: implement responsive images throughout a legacy Rails application. Back then, the app was sending disproportionally large image files over to web browsers regardless of client device and viewport characteristics. Users had to bear the burden of <a href="https://www.maxcdn.com/one/visual-glossary/page-load-time/">prolonged load times</a> and an overall bad experience which contributed towards decreasing conversion rates.</p><p>To solve this problem, we provisioned an on-the-fly image server to perform image manipulations in real time and wired it up to a <a href="https://en.wikipedia.org/wiki/Content_delivery_network">CDN layer</a>. Our first task was to assess whether the concept would work on a small portion of the product, which was far away from the home page and thereby did not have as much traffic.</p><h3>The first version</h3><p>With all the basic infrastructure in place, we looked for gems to help us implement responsive images but none proved to be suitable for our use case. We then started developing our own solution to fulfill the following requirements:</p><ul><li>One Image (AR model) maps to one responsive image (one-to-one).</li><li>Responsive images can have different formats: HTML, CSS and JSON.</li><li>Formats can be shared among internal and external apps for preloading, JS integration and other purposes.</li></ul><p>If you are wondering, a <strong>responsive image</strong> consists of a set of images where each one applies to a different screen size or device-pixel-ratio.</p><p>After some work, a ResponsiveImage class similar to the following was born:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2a5c467acadd30c7d00f4d82066aa31/href">https://medium.com/media/a2a5c467acadd30c7d00f4d82066aa31/href</a></iframe><p>As you may have figured, this class aims to provide functionality for subclasses to define and gather image versions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18b0b0a9e2702c80dbc1f51a706b5430/href">https://medium.com/media/18b0b0a9e2702c80dbc1f51a706b5430/href</a></iframe><p>Take line 2 for example: it declares an image of 173x130 pixels which is meant to be displayed on viewport widths between 0 and 599 pixels. Also, the inherited hook automatically declares an :original version on all subclasses. Among other utilities, each version is meant to generate a distinct URL to the image server requesting a crop corresponding to the declared dimensions:</p><pre># Returns a URL for the :sm version<br>responsive_image.url(https://medium.com/:sm)</pre><p>In the end, a ResponsiveImage object is nothing but a proxy for obtaining different representations, which functionality gets delegated away to specialized objects:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee9172ff58074ed53deeb849cf7da419/href">https://medium.com/media/ee9172ff58074ed53deeb849cf7da419/href</a></iframe><p>Finally, here is an example usage:</p><pre>&lt;%= FreebieMainImage.new(freebie.main_image).to_picture %&gt;</pre><p>This ERB code outputs a <a href="https://www.html5rocks.com/en/tutorials/responsive/picture-element/">picture tag</a> HTML containing display rules and URLs for all versions declared in FreebieMainImage.</p><h4>A touch of convenience</h4><p>That implementation proved to be a great fit for our problem, but using it was not without friction. Among other issues, we needed to reuse the same responsive image over a single endpoint, and instantiating objects more than once did not feel right.</p><p>Using the controller for this purpose would have been a bad move since it would encourage bloating all others:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b0af2fdef720bb37e8b641a20f1cfb85/href">https://medium.com/media/b0af2fdef720bb37e8b641a20f1cfb85/href</a></iframe><p>We needed an abstraction to make this recurring code easier to work with. After thinking for a while, we came to the conclusion that a factory to group responsive images by model seemed like an appropriate solution.</p><p>Here’s the sketch: given our Freebie model has one main_image, our collection automatically figures the right presenter for it (FreebieMainImage) and delivers the result through a hash-like interface.</p><p>Let’s apply some <a href="http://blog.adrianbolboaca.ro/2016/04/programming-by-wishful-thinking/">programming by wishful thinking</a> and picture how our imaginary code ought to be used:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb2464da3c4e0bb408bd9f5ea15e4b10/href">https://medium.com/media/bb2464da3c4e0bb408bd9f5ea15e4b10/href</a></iframe><p>Finally, here’s the implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ead9feabfa619583570e476e886b3349/href">https://medium.com/media/ead9feabfa619583570e476e886b3349/href</a></iframe><p>As you can see, we are using a <em>Railsy</em> convention to find the responsive class of an image: if the model name is Freebie and the image name is main_image, we then look for a class named FreebieMainImage.</p><p>The following method at FreebiePresenter makes the code even more accessible and avoids further pollution of controllers:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/30dadea490fbc0b9195b40f68cf46c83/href">https://medium.com/media/30dadea490fbc0b9195b40f68cf46c83/href</a></iframe><p>Finally, here’s how to use it in the views:</p><pre>&lt;%= @freebie.images[:main_image].to_picture %&gt;</pre><h4>Advantages of the first version</h4><p>The launch gone smooth and the code was technically adequate, because:</p><ul><li>Concerns were kept separate and we did not bloat the model with responsive configuration. That would be more akin to a classic Rails solution.</li><li>The ResponsiveImage class was not coupled to any particular Image.</li><li>The version method proved to be a great and nifty macro.</li><li>Although palliative, ResponsiveImageCollection fulfilled the needs of the first launch: it mapped resources one-to-one but it did not couple the core system in any way.</li></ul><p>Good enough, ship it!</p><h3>The second version</h3><p>The time came around to implement the system in a wider range of pages, right after our successful POC got deployed. Additionally, adapting the core was necessary to take into account a newfound complexity:</p><ul><li>One Image maps to many ResponsiveImage and vice-versa (many-to-many).</li></ul><p>We did some planning and went on to work on these new changes.</p><h4>Realizing the symptoms</h4><p>During our first iteration, we repeatedly found the need to declare responsive subclasses:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e80c7cfd1a1afeaba94893b476c09bd/href">https://medium.com/media/7e80c7cfd1a1afeaba94893b476c09bd/href</a></iframe><p>Then an obvious realization emerged: creating a class for <em>each and every</em> responsive image would get exhausting pretty quickly.</p><p>We did not anticipate the pain because at first there were just a few configurations to deal with. <strong>This is OK</strong>: we released the minimal amount of code to solve our problem, but the solution had to evolve to accommodate newfound requirements and eliminate rough edges.</p><p>After asking a few questions to ourselves, an interesting fact turned up: the role of our subclasses was to gather and centralize <strong>data</strong>.</p><blockquote>Wait a minute, isn’t inheritance mostly about behavior?</blockquote><p>That’s right: inheritance is best for specializing behavior where <em>a</em> “Y is a X” kind of relationship exists. Of course, our subclasses did not meet those requirements: instead they acted as configuration hubs supplying <strong>data</strong> over to inherited methods.</p><blockquote>Never should the role of inheritance be *just* to <strong>share</strong> methods and implementation details. This kind of misuse usually points toward design improvements.</blockquote><p>As a side effect, our approach generated complexities not apparent at first sight such as looking for artifacts by class name. This is OK when dealing with <a href="https://en.wikipedia.org/wiki/SOLID_(object-oriented_design)">SOLID</a>-oriented code, but it did not happen to be our case.</p><h4>The solution</h4><p>Our problem seemed more suited to a registry that provides configuration to a factory. Didn’t get it? So bear with me.</p><p>The first step to refactor our solution was to start moving versions from class-level to instance-level, though not removing the class method yet:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/595/1*qe2OpdJUK-jbaezpjrvHFw.png" /></figure><p>Great, everything worked just as before and it was possible to instantiate responsive images on-the-fly without the bureaucracy of subclasses:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0181c9c0a6ef8bfc623d714dae6a53f3/href">https://medium.com/media/0181c9c0a6ef8bfc623d714dae6a53f3/href</a></iframe><p>Since we started moving versions into an instance method, the next step was to change all call-sites from class method to instance method (we will not present this step here).</p><p>However, we were still using subclasses:</p><pre>FreebieMainImage.new(freebie.main_image)</pre><p>Eliminating these artifacts proved to be a bit more difficult. First of all, we created a registry to allow getting rid of subclass-centric configuration:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3d4be0dda2797303e968cef786914abe/href">https://medium.com/media/3d4be0dda2797303e968cef786914abe/href</a></iframe><p>Then we moved versions of all subclasses onto it. For instance, the following code can be placed on a Rails initializer:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9d5752d207ea8bcf31f9a14b91de1c5/href">https://medium.com/media/c9d5752d207ea8bcf31f9a14b91de1c5/href</a></iframe><p>As you can see, the add method receives a configuration ID and an array of version information which gets mapped away to Struct objects.</p><p>Next, we changed ResponsiveImageCollection to search for config keys instead of subclasses:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/674/1*QVIZIAoxci46hMYVy_rUjQ.png" /></figure><p>Finally, we were able to definitely delete ResponsiveImage.version and ResponsiveImage.inherited methods. Our class got much simpler:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/598/1*2aLQYUktpqfnSOoe-AZoEA.png" /></figure><p>But we were not over yet.</p><h4>One last coupling</h4><p>Refactoring our solution was relatively easy, but there were still problems. What if we wanted to reuse the same responsive configuration <strong>twice</strong>? The short answer is we couldn’t, because our collection class was using a hardcoded naming scheme to look up configurations.</p><p>For instance, if we had a Project model and wanted to declare versions for its main_image, we would have to use a project_main_image key:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/19d4db3d491f0641b9b16209b7b1fc0d/href">https://medium.com/media/19d4db3d491f0641b9b16209b7b1fc0d/href</a></iframe><p>This was inflexible and did not scale up, not to mention the naming scheme was obscure and hard to remember.</p><p>What if we had a way to explicitly map images to their responsive counterparts? In that case, we would be able to specify and repeat any combination and quantity of elements.</p><p>Firstly, we created a CollectionConfig class similar to ResponsiveConfig:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/644cd0a3f5d8129296738d7e7a95fdbe/href">https://medium.com/media/644cd0a3f5d8129296738d7e7a95fdbe/href</a></iframe><p>Then we configured our collection mappings like so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/180017774a42c5155b01091d04c05667/href">https://medium.com/media/180017774a42c5155b01091d04c05667/href</a></iframe><p>And finally, we changed our collection class to interpret these mappings:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/662/1*Rm5R771cgdqkBf6os3Gmeg.png" /></figure><p>Awesome! In doing that we were finally able to reuse the main_image config on a random_image (or any other image for the matter):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ecf3cdcf826b79dfeda8f42e0f835dc3/href">https://medium.com/media/ecf3cdcf826b79dfeda8f42e0f835dc3/href</a></iframe><p>Using the system was still very easy, not to mention the ERB call sites did not change a tiny bit:</p><pre>&lt;%= freebie.images[:main_image].to_picture %&gt;</pre><p>Of course, our collection class could have been made more flexible. For example, we could have gotten rid of the model coupling: why does a collection need to be coupled to a model anyway?</p><p>However, do we need to? <strong>Nope, it’s a feature! </strong>Other kinds of collections can easily be created, and the underlying system is flexible enough to allow for just that.</p><h3>Wrap up</h3><p>The code in here was considerably changed to fit into main theme of this blog post. Also, we did not go over the real complexity faced while implementing the solution.</p><p>Nevertheless, the key ideas here are:</p><ul><li>If the amount of change you need to perform on a task is huge, tackle it in small chunks and <em>start small</em>.</li><li>Don’t try to guess the future: write just the amount of code your solution needs. Listen to the pain and allow your system evolve naturally.</li><li>Inheritance is not bad, but it’s also not suited for many problems.</li><li>Beware when subclasses are used with the sole purpose of sharing data. Be attentive to their best usages and keep asking questions to yourself.</li></ul><p>Thanks for reading and have a great day.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b6fe4db58b18" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeminer-42/refactoring-ruby-from-subclass-to-registry-b6fe4db58b18">Refactoring Ruby: From Subclass to Registry</a> was originally published in <a href="https://medium.com/codeminer-42">The Miners</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Towards Minimal, Idiomatic, and Performant Ruby Code]]></title>
            <link>https://medium.com/codeminer-42/towards-minimal-idiomatic-and-performant-ruby-code-f3fc6aed3c94?source=rss-84180f96c985------2</link>
            <guid isPermaLink="false">https://medium.com/p/f3fc6aed3c94</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Thiago Araújo Silva]]></dc:creator>
            <pubDate>Mon, 06 Mar 2017 14:31:18 GMT</pubDate>
            <atom:updated>2017-03-11T21:32:11.622Z</atom:updated>
            <content:encoded><![CDATA[<h4>Debunking some popular Ruby idioms</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/959/1*Qc0XxYm-qAZL-7tjjlNfrg.png" /></figure><p>I try to embrace a particular way of working with code: it should be minimal, idiomatic, and performant <em>by default</em>. Sometimes it is necessary to trade performance for readability, or readability for performance, or even break the deal if the trade is not worth it. It is possible to attain an optimal balance among all of these factors, as long as the goal remains ingrained in small decisions that we make while coding.</p><p>We will go over some specific examples that may benefit from a straight “no” answer <em>by default</em>, as they do not pose a worth trade most of the times. If you are not already into this mindset, consider getting into it.</p><h3>Minimal: Defining unnecessary methods</h3><p>Let’s stick to “attribute readers”, which are also known as “getters” in other programming languages. Take this code for example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c8580f5a4568f3f154ef14ef5840b6c/href">https://medium.com/media/3c8580f5a4568f3f154ef14ef5840b6c/href</a></iframe><p>Assuming that all clients of this code just use the name method, the first_name and last_name readers should not really exist. They are nothing but slop unnecessarily polluting the public interface of our object.</p><p>As an <em>application interface</em> designer, you should definitely care about which methods are meant to be publicly exposed or not — and if you have control over the call sites, it is best to publish only methods that are indeed used by consumers. This kind of minimalism yields benefits and tends to make a codebase well-rounded and easier to evolve over time.</p><p>I have frequently stumbled across such sloppiness while performing refactorings and searching for occurrences of these methods around the code base, only to find out they are not used anywhere else but internally. As you can see, this is <em>also</em> about communication.</p><p>Let us go farther:</p><blockquote>All code should exist with a good reason</blockquote><p>And how about making the readers private? It is a popular technique, but is it any good? Let’s see:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/33e538b7cf7a2cb30a7d57b8c984b561/href">https://medium.com/media/33e538b7cf7a2cb30a7d57b8c984b561/href</a></iframe><p>Well, this change introduces a subtle problem: <strong>more code</strong>. That may be a bad idea if it does not help with readability. Let’s run our file in the Ruby interpreter with the -W flag:</p><pre>$ ruby -W person.rb<br>person.rb:10: warning: private attribute?<br>person.rb:10: warning: private attribute?</pre><p>That’s right, we asked for Ruby’s opinion and it warned us against our redundancy. We are adding extra lines of code to no substantial benefit, as we could have just referenced the instance variables directly:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/726a955ab5d057fd09399a4e9adbba64/href">https://medium.com/media/726a955ab5d057fd09399a4e9adbba64/href</a></iframe><p>As you may already know, attr_reader dynamically defines a method which returns an instance variable of the same name:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ff739249a955ad013cd4f28ca5096f8/href">https://medium.com/media/6ff739249a955ad013cd4f28ca5096f8/href</a></iframe><h4>What if there is a typo in the ivar?</h4><p>Let’s make that assumption with some code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/71010186928bfc75d62df21dcd339bec/href">https://medium.com/media/71010186928bfc75d62df21dcd339bec/href</a></iframe><p>This version is semantically incorrect due to a typo on @firs_name, but to the surprise of many it does not fail with a NameError. Why? Because undefined <em>ivars</em> return nil in Ruby, and nil.to_s results in an empty string.</p><p>To be honest, to this date I have only seen this carelessness occur in sloppy code with no tests, not to say it only happens when interpolating <em>ivars</em> within strings.</p><p>The following example, in turn, provides a more useful error message:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/53a7075c9fc2ec46f727ff4637494bb7/href">https://medium.com/media/53a7075c9fc2ec46f727ff4637494bb7/href</a></iframe><p>As opposed to a NameError in the case of a private reader, which is even more precise:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cce1f5ed78caa58cb7e7b3fcf7859d31/href">https://medium.com/media/cce1f5ed78caa58cb7e7b3fcf7859d31/href</a></iframe><p>Fortunately, both errors indicate the most relevant information to help us solve the problem: the line number — so, having a <em>slightly</em> improved error message <strong><em>in case</em></strong> a typo ever sneaks in does not sound like a good trade to me.</p><p>The error may explode somewhere else within the class if we pass a nil <em>ivar</em> to another method, but still it gets easy to fix.</p><h4>But I want to provide an extension point</h4><p>A private getter may provide an extension point <em>in case</em> we require custom logic for the attribute in the future. Consider the following hypothetical change:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7f346b6c4528bbc1e12842ea5779877e/href">https://medium.com/media/7f346b6c4528bbc1e12842ea5779877e/href</a></iframe><p>Heads up if you spot “<em>in case…</em>” or “<em>in the future…</em>” amidst a justification for code to exist. Why create such an extension point for a private attribute? Remember: the internals are under your control, hence I advise you to postpone this kind of “preventive” behavior until really necessary.</p><p>Truth to be said, using a private reader won’t make your code DRY if you are concerned about referencing the <em>ivar</em> more than once. Changing it to a method is just one search and replace away.</p><blockquote>DRY is more about the big picture</blockquote><p>There is a beautiful and minimal simplicity in using <em>ivars</em> directly, not to say they are easier to discern than <em>barewords</em>. Just try to keep <em>ivar</em> assignments on the initializer, and your class will become easier to maintain.</p><h3>Idiomatic: Converting blocks to procs</h3><p>The following each method leverages a very common Ruby idiom:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/180704d918ff5742876746dd770fe4e7/href">https://medium.com/media/180704d918ff5742876746dd770fe4e7/href</a></iframe><p>It seems innocuous, right? Well, not so much. There is a performance hit there which should not be ignored. It turns out the each method converts a block to a proc object behind the scenes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c3f0bd98f3e3d66cdf70164a75dab639/href">https://medium.com/media/c3f0bd98f3e3d66cdf70164a75dab639/href</a></iframe><p>And what is the problem? Well, a proc is a full-blown object, whereas a block is one of the few Ruby constructs that is not an object — actually, it is tuned to be performant and it does not have a callable interface nor does it respond to any methods.</p><p>There is a cost involved in this conversion, but we can easily avoid it by using an old’n’trusty block:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ab7fb18caa7dfadd9bc76b76c05fb6a/href">https://medium.com/media/5ab7fb18caa7dfadd9bc76b76c05fb6a/href</a></iframe><p>Let’s run a benchmark to compare both alternatives:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9402bc717e6922fc5b29a5cfad766142/href">https://medium.com/media/9402bc717e6922fc5b29a5cfad766142/href</a></iframe><p>These results show that converting a block to a proc is about 1.44 times slower:</p><pre>Warming up --------------------------------------<br>               block    79.756k i/100ms<br>       block to proc    59.273k i/100ms<br>Calculating -------------------------------------<br>               block      1.268M (± 5.4%) i/s<br>       block to proc    878.862k (± 6.9%) i/s</pre><pre>Comparison:<br>               block:  1268320.3 i/s<br>       block to proc:   878862.3 i/s - 1.44x  slower</pre><p>The numbers may as well be interesting, but one thing you have to keep in mind regardless is: <strong>the code works harder</strong>. If there was a substantial benefit to this I would just say “OK, no big deal”. But is there? Is the other way around problematic?</p><p>To be fair, there is still a syntactic advantage to using a &amp;block argument: the delegation is transparent. For instance, the following example breaks if we do not pass a block:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5ab7fb18caa7dfadd9bc76b76c05fb6a/href">https://medium.com/media/5ab7fb18caa7dfadd9bc76b76c05fb6a/href</a></iframe><pre>custom_collection.rb:9:in `block in each’: no block given (yield) (LocalJumpError)</pre><p>But it should have returned an enumerator, right? If not given a block, any idiomatic Ruby iterator is meant to return an enumerator.</p><p>So, why does the block-to-proc alternative return an enumerator? Because it delegates away the input block, and since the <em>delegatee</em> happens to be Array#each we get this benefit for free. It works like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aff090a741c242b1303d0fe71c553f6b/href">https://medium.com/media/aff090a741c242b1303d0fe71c553f6b/href</a></iframe><p>Fortunately, improving the second example consists in just one more line of code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a2016c0965db711e650ab128aa69f9dd/href">https://medium.com/media/a2016c0965db711e650ab128aa69f9dd/href</a></iframe><p>Now our method has the same behavior as a proc-to-block delegation and it returns an enumerator if we pass no block to it.</p><p>And here is an equivalent alternative:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1eaf843199de9820ec66633a536543a6/href">https://medium.com/media/1eaf843199de9820ec66633a536543a6/href</a></iframe><p>It has a few more lines, but it is still readable, elegant, maintainable, and faster than our &amp;block option. Now we can chain iterators to perform complex transformations:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cd7aa48eaf84e43c0fa958fb64302db/href">https://medium.com/media/1cd7aa48eaf84e43c0fa958fb64302db/href</a></iframe><blockquote>When possible, make your code behave like a native citizen</blockquote><p>And when is it good to use a &amp;block argument? When the code within the block needs to be stored for later use, due to a block falling out of scope after a method exits:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dbba4d3722da1f0716d222462642d7d6/href">https://medium.com/media/dbba4d3722da1f0716d222462642d7d6/href</a></iframe><h3>Performant: Method objects emulating first class functions</h3><p>Ruby does not have first class functions, so how do we compensate that deficiency? That’s right, by extracting method objects. Follows a silly example specifically tailored to illustrate this point:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/273fdaf1d1982ba3d05d4926db0a08dd/href">https://medium.com/media/273fdaf1d1982ba3d05d4926db0a08dd/href</a></iframe><p>This object takes an array of numeric values and returns a new one with each number multiplied by two. Notice how call converts the multiply_by_two method into an object that can be passed over to map.</p><p>When I see code like this written in Ruby, I automatically assume it is trying to be concise and reduce verboseness. However, does it read well? Does it meet that goal? I don’t think so. The &amp;method call is noisy and it does not look like idiomatic Ruby — it goes against the nature of the language and how it wants to be used in such cases.</p><p>Let’s face it: Ruby is not JavaScript, so you should not pass functions around indiscriminately. We can improve this code with “blocks”, an idiomatic Ruby feature that is ideal for this situation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2c2c8b110ea8def194005604121d777/href">https://medium.com/media/b2c2c8b110ea8def194005604121d777/href</a></iframe><p>This is considerably more expressive in my opinion. It is not <a href="http://xahlee.info/comp/point-free_programing.html">point-free</a> like the &amp;method alternative, but you can use a splat if you need more resilience:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae39d258695272b6b657b0c876b35cee/href">https://medium.com/media/ae39d258695272b6b657b0c876b35cee/href</a></iframe><p>But we are not at the bottom line yet. There is something more important than a stylistic issue: extracting a method comes at a cost, and as a wary programmer you should be aware of that.</p><p>Turns out this code is extracting off a method object <strong>and</strong> converting it to a block afterwards (hence the &amp; character). Let’s run a benchmark comparing “block” versus “method object”:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/76e414c11a971ac977dc5ca0f65548aa/href">https://medium.com/media/76e414c11a971ac977dc5ca0f65548aa/href</a></iframe><p>Now onto the results:</p><pre>Calculating -------------------------------------<br>          with block    46.214k i/100ms<br>         with method    21.740k i/100ms<br>-------------------------------------------------<br>          with block    806.459k (± 7.0%) i/s -      4.021M<br>         with method    285.775k (± 7.4%) i/s -      1.435M</pre><pre>Comparison:<br>          with block:   806459.0 i/s<br>         with method:   285775.4 i/s - 2.82x slower</pre><p>As you can see, method object is<strong> 2.82 times slower</strong> than block. This may not seem like a big deal if the code runs just a few times, but it may add up over the course of a real-world program. If we can avoid it, why not?</p><h4>Ruby is slow, why should I care?</h4><p>It is not <em>that</em> slow and I would dare to say it has acceptable performance for a dynamic language. This mindset is dangerous and may potentially turn a fast program into a slow one over time. As wary programmers, we should find a sweet spot between performance and readability, and avoid doing unnecessary work whenever we can.</p><blockquote>Avoid doing more work if the trade is not worth it</blockquote><p>There are still nice use cases for Object#method, and most of them refer to reflection and metaprogramming. We can ask a method for its source location:</p><pre># [&quot;number_doubler.rb&quot;, 22]<br>p list.method(:call).source_location</pre><p>Or for its arity:</p><pre># 0<br>puts list.method(:call).arity</pre><h3>Conclusion</h3><p>I could have used an abstract and general prose here, but instead I chose to present content that is somehow relevant to the theme. That said, there is a lot more ground to cover!</p><p>I hope this post challenges you to think deeper about how your code looks and works under the hood, and to stop thinking “<em>Ruby is slow, I don’t care</em>”. If I have the opportunity, I hope to go over more examples in the near future.</p><p><strong>UPDATE 1, 2017–03–10</strong>: As <a href="https://twitter.com/pda/status/839980368946110464"><strong>Paul Annesley</strong>‏</a> and <a href="https://twitter.com/hazula/status/839984742632214529"><strong>Benjamin Fleischer</strong>‏</a> pointed out on Twitter, the private attribute warning <a href="https://bugs.ruby-lang.org/issues/10967">has been removed as of Ruby 2.3</a>. I did not really want to convey the meaning that they are <em>wrong</em> or <em>invalid</em>, but instead to provide a compelling argument on why I think they are superfluous.</p><p>Ruby is about freedom, so I think the team’s decision to remove the warning makes sense. Matz mentioned they did not think of <em>self</em> as a receiver for attribute readers, which implies the warning was meant to prevent them from being accidentally hidden beneath the private interface. Having <em>self</em> as a receiver is a semantically <em>valid</em> case, though in my opinion it is usually not worth it.</p><p><strong>UPDATE 2, 2017–03–10</strong>: It’s important to make it clear that benchmarks of this post are MRI-specific, so they may or may not apply to other Ruby implementations as <a href="https://medium.com/u/b3d5a4fbc3f">Michael Kohl</a> pointed out in the comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f3fc6aed3c94" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeminer-42/towards-minimal-idiomatic-and-performant-ruby-code-f3fc6aed3c94">Towards Minimal, Idiomatic, and Performant Ruby Code</a> was originally published in <a href="https://medium.com/codeminer-42">The Miners</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cracking the Box Open with Module Factories]]></title>
            <link>https://medium.com/codeminer-42/cracking-the-box-open-with-module-factories-2ef048193a7e?source=rss-84180f96c985------2</link>
            <guid isPermaLink="false">https://medium.com/p/2ef048193a7e</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[metaprogramming]]></category>
            <dc:creator><![CDATA[Thiago Araújo Silva]]></dc:creator>
            <pubDate>Mon, 19 Dec 2016 14:56:18 GMT</pubDate>
            <atom:updated>2017-06-05T17:20:17.417Z</atom:updated>
            <content:encoded><![CDATA[<h4>About the lesser-known Ruby Module Factories</h4><p>Metaprogramming is one of Ruby’s most powerful, intriguing and hard-to-grasp features. Ruby has a deep kind of truth that I could not yet find in any language, <em>similar</em> to the chicken &amp; egg dilemma that we find in real life: an object is generated from a class, but a class is an object itself. Once you understand the truth behind this statement, everything makes perfect sense: from the beautiful object model to the expressive lines of code we can achieve with the language.</p><p>This post discusses a very useful feature that only a few Ruby programmers know: the <strong>module factory</strong>. Before getting to that, we will dig into the object model to acknowledge how modules work under the hood, then we will walk through some possible use cases of modules and how these compare to module factories.</p><h3>An example to start off</h3><p>Suppose we have a Ruby on Rails application with a polymorphic Image model as a single source of truth for all images.</p><p>Initially, requirements demand some of our models to be linked to one main_image each. To solve this problem, we can define an Imageable module that knows how to extract the right record from the images table and deliver an Image instance.</p><blockquote>A good use case for modules is to share simple glue functionality among similar objects, especially when it feels like the functionality belongs to the object itself.</blockquote><p>Setting aside has_one relationships for a reason, this is the simplest code that solves our problem:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0e7561df4cd61914f8cf64eba37634c3/href">https://medium.com/media/0e7561df4cd61914f8cf64eba37634c3/href</a></iframe><p>And using the module is very straightforward:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d38fe75963b1cbd5c7250af9df7ae319/href">https://medium.com/media/d38fe75963b1cbd5c7250af9df7ae319/href</a></iframe><p>Now Project is set to have_many images, and we can quickly obtain the main_image of any instance as if it was a normal attribute. Don’t worry about how records arrive in the database, assume that only a <em>getter</em> does the work we need just fine.</p><h3>When the truth is unveiled</h3><p>But guess what? It turns out that module Imageable is nothing but pure syntactic sugar provided by Ruby, and what the language is doing under the hood is creating an instance of the Module class. Let’s visualize the same code with another pair of eyes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6ee43b31c4a44192f3cf579f9ce1cfe3/href">https://medium.com/media/6ee43b31c4a44192f3cf579f9ce1cfe3/href</a></iframe><p>You can think of modules as objects with a particular kind of power: they allow you to write a collection of methods that can be <strong>shared</strong> among classes and other modules. The way to share this collection is via the include statement:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/849a1d4b01f83914a2f0fe50c462a797/href">https://medium.com/media/849a1d4b01f83914a2f0fe50c462a797/href</a></iframe><blockquote>&quot;extend&quot; does the same job as “include,” but it acts in a different context. We will skip “extend” in this post.</blockquote><p>When you “define” a method in a module, what you are really doing is <em>writing</em> it to a special kind of “template,” a collection called “instance methods.” Think of it as a super power conceded by the language, something that only module instances can do.</p><p>By including the module in a class, you are just “mixing in” its instance methods into the class’ own instance methods collection:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4028ca9856d28839b1897fc7ec228629/href">https://medium.com/media/4028ca9856d28839b1897fc7ec228629/href</a></iframe><p>And what about classes? <strong>A </strong><strong>class is just a specialization of a </strong><strong>module with factory powers</strong>; hence it’s able to do something the latter can’t do: create objects provided with these instance methods.</p><blockquote>A module is just a stripped-down class, but it possesses the most basic functionality any class needs: the ability to hold instance methods.</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9f610e4624e55e34ceb663e3bbcb0fc9/href">https://medium.com/media/9f610e4624e55e34ceb663e3bbcb0fc9/href</a></iframe><p>But wait, isn’t a module an object? Let’s get back to the deeper truth:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a76251b16c1a4dcf1be8c4ccba33029/href">https://medium.com/media/6a76251b16c1a4dcf1be8c4ccba33029/href</a></iframe><h3>Getting deeper with Module Factories</h3><p>Since a module is an object, it must have been generated from a class. And what class is it? Module. Remember the Module.new above? Classical object oriented programming, huh? The definition of a Module exists somewhere under the covers, and it might as well look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3aa24aaaddae65d4c8e7ac9483eb17cb/href">https://medium.com/media/3aa24aaaddae65d4c8e7ac9483eb17cb/href</a></iframe><blockquote>Ruby defines “Module” automatically for us, right when our program boots up.</blockquote><p>However, this is not just an object model fairy tale: Actually, it’s sort of ordinary at a language level. The Module class is a factory, right? Because it’s a class, we can subclass it to create our own factories:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9346f9b419052837aa710ed8d0baec6/href">https://medium.com/media/b9346f9b419052837aa710ed8d0baec6/href</a></iframe><p>And we can instantiate a custom module just like any other object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d3cbafd8594bee486ce0b9b26cd37ac/href">https://medium.com/media/0d3cbafd8594bee486ce0b9b26cd37ac/href</a></iframe><p>In this example, the <em>initializer</em> of the Module class got overwritten with a new one that defines instance methods on-the-fly in every created module! Otherwise, it would have been set in stone forever:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/29f4ce02e1ff22b7fb9eb64c98d4702e/href">https://medium.com/media/29f4ce02e1ff22b7fb9eb64c98d4702e/href</a></iframe><p>Or, more traditionally:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49fe3f775d947037ce8f18a0e7c2a860/href">https://medium.com/media/49fe3f775d947037ce8f18a0e7c2a860/href</a></iframe><p>With the dynamic version, we can <strong>also</strong> create a module that responds to four, five and six on-the-fly, see?</p><p>The conventional initialize method is a key factor to building great module factories. Without it, our factory would have looked kinda strange:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ebcb74eb7b7ab7048921b8cfe8733cc/href">https://medium.com/media/9ebcb74eb7b7ab7048921b8cfe8733cc/href</a></iframe><p>The ModuleGenerator example isn’t particularly useful, so let’s revisit the Imageable concern.</p><h3>Module Factories for the greater good</h3><p>Our requirements for Imageable have changed, and now some of our models need other kinds of one to one image fields. A single main_image field won’t do anymore.</p><p>To solve this problem, we can &quot;convert” Imageable from a module instance to a module factory:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae359d5ebe10c117bd847c6c216a25ba/href">https://medium.com/media/ae359d5ebe10c117bd847c6c216a25ba/href</a></iframe><p>Now we can have as many image fields as we want in our model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ca1a778d4b5a5c3aa89ecc9dfa6cd2f4/href">https://medium.com/media/ca1a778d4b5a5c3aa89ecc9dfa6cd2f4/href</a></iframe><p>But we can do even better! Since we are using a class to create a module, why not use private methods to organize our logic?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/10b27c5a34bd9fe7fda7dd95817c3598/href">https://medium.com/media/10b27c5a34bd9fe7fda7dd95817c3598/href</a></iframe><p>It’s great that we are now able to name each chunk of code, thanks to our good ’n’ old class organization tools. Now it’s easier to grow our logic without turning it into a mess.</p><p>Of course, non-dynamic methods can use module_eval instead of define_method for better readability:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/771efae6f40b52dcb704f0d60278a4a3/href">https://medium.com/media/771efae6f40b52dcb704f0d60278a4a3/href</a></iframe><h3>The dirty block approach</h3><p>I’ve seen a few projects solving the same problem roughly like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/791cccfe438b28b5c11d71756039c13e/href">https://medium.com/media/791cccfe438b28b5c11d71756039c13e/href</a></iframe><blockquote>The “Module” class’ constructor provided by Ruby can evaluate a block with the same effect as “module_eval”.</blockquote><p>As you can see, a “factory” singleton method is being defined within a module, and it returns <em>another</em> module with dynamically generated instance methods.</p><p>The problem with this code is that it tends to grow disorderly and out of bounds. Imagine two, three, four, ten additional dynamic method definitions within the same block of code. Would you be able to tell exactly what they are, or even what they do? Probably so, but it would take <strong>more time</strong> to figure it out. Comments would likely help, but they wouldn’t exempt things from being ugly.</p><p>With module factories, we can use private methods to aid in organization, whereas with the dirty block approach we simply can’t. And this is a problem.</p><h3>The macro approach</h3><p>The “macro” approach is a familiar style used throughout Rails and other projects: the idea is to provide the target class with singleton methods that are responsible for defining other methods within the class’ instance collection. Let’s change Imageable to use this approach:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2eda4e530bedc63dffad603ae8a2dc05/href">https://medium.com/media/2eda4e530bedc63dffad603ae8a2dc05/href</a></iframe><p>This code is not bad <em>per se</em>, but there’s still a potential problem with it: suppose one of the macros needs to define <em>more than one</em> instance method. In that case, we would have gotten stuck with chunks of complex code we wouldn’t be able to name, and it would be harder to read it overall.</p><p>We could split the logic to other macros, but that would pollute the target class’ interface with methods it wouldn’t ever need to use! Moreover, we would still be polluting the class with singleton methods anyway (has_one_image), so it’s not an approach I would call “tidy”.</p><p>The upside of macros is that they are readable, but if you’ve seen Rails models in real life you’ve probably noticed they tend to be full of these nifty calls that read like <em>DSLs</em>, and it may get to a point where you don’t know which macro belongs to which module anymore.</p><h3>The advantages of Module factories</h3><p>Module factories are relatively unusual in the Ruby world, but I’d wish they weren’t because they solve some problems in a very elegant fashion:</p><ul><li>They allow to organize on-the-fly instance methods definitions.</li><li>They are tidy and don’t pollute the target class with singleton methods.</li><li>They provide encapsulation for the factory logic.</li><li>They are self-contained: all instance methods can be written directly in the module.</li><li>They can be as readable as macros.</li><li>You can pass options to a plain old constructor of a plain old class. Now you know to which module a feature belongs, instead of trying to guess what’s the origin of a macro you find in a class body, amidst a mess of other macros.</li></ul><h3>Wrap up</h3><p>Metaprogramming is cool, but it should be used with care. It’s a very powerful feature appropriate to aid in framework code, even though there are nice use cases regarding application logic. I even tried to illustrate a good example with Imageable.</p><p>And you should also think twice before using modules as “concerns” (as known in the Rails community). There are usually better ways to solve the same problem, like object composition, for example. Nevertheless, it’s a no-brainer for simple glue code and convenient attribute emulation.</p><p>That said, if all you have is a hammer, everything looks like a nail.</p><p><em>I hope you have enjoyed this post. If you have any questions, just hit me up in the comments!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2ef048193a7e" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeminer-42/cracking-the-box-open-with-module-factories-2ef048193a7e">Cracking the Box Open with Module Factories</a> was originally published in <a href="https://medium.com/codeminer-42">The Miners</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go Full Stack Rails — The Frontend part 3]]></title>
            <link>https://medium.com/codeminer-42/go-full-stack-rails-the-frontend-part-3-a973a7b227f1?source=rss-84180f96c985------2</link>
            <guid isPermaLink="false">https://medium.com/p/a973a7b227f1</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[functional-programming]]></category>
            <category><![CDATA[es6]]></category>
            <dc:creator><![CDATA[Thiago Araújo Silva]]></dc:creator>
            <pubDate>Mon, 12 Dec 2016 14:14:05 GMT</pubDate>
            <atom:updated>2016-12-14T14:59:03.972Z</atom:updated>
            <content:encoded><![CDATA[<h4>A pipeline of functional transformations</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/844/1*gHxRIfJoujL5WIPFenFh9Q.jpeg" /></figure><p>Although not mandatory, you can catch up with previous episodes if you haven’t already:</p><ul><li><a href="https://blog.codeminer42.com/go-full-stack-rails-the-backend-a94b4d0e8897">The Backend Part 1</a>: Working on the backend, exploring requirements and building a Rails controller to deliver timeline tweets</li><li><a href="https://blog.codeminer42.com/go-full-stack-rails-the-backend-part-2-339db75a5db0">The Backend Part 2</a>: Building a timeline wrapper to isolate external dependencies</li><li><a href="https://blog.codeminer42.com/go-full-stack-rails-the-frontend-part-1-1b889c919b4a">The Frontend Part 1</a>: A brief introduction to test-driven frontend development</li><li><a href="https://blog.codeminer42.com/go-full-stack-rails-the-frontend-part-2-e91ac08b40a">The Frontend Part 2</a>: About ES6 Promises and improving Promise-based specs</li></ul><p>Each part of this tutorial touches on matters around a full-stack application written with Rails and ES6. The application itself may certainly look cool, but I’d like to call out a few aspects much more important than that. So far, we’ve been discoursing about a few questions, although briefly and within the context of an actual application:</p><ul><li>As developers, how do we get to our goals? Which processes do we leverage to get our applications working with the least amount of defects?</li><li>A full-stack mindset: even if you are specialized in one part of the stack, the most valuable move you can make to your web development career is to get the big picture and acquire proficiency in both areas, therefore being up to any task.</li><li>How to write modular and easy to understand code by taking advantage of tried and true practices all around the stack, everything backed by good tests. Bad tests can be damaging to any project and provide no value at all.</li></ul><h3>How should we deal with JavaScript in Rails apps?</h3><p>Before getting to the code, I’d like to carry on with an important reflection. How should we deal with JavaScript in a Rails app?</p><p>I can certainly say something about classic Rails developers, but it’s also true in general: historically, they did not care much about writing maintainable JavaScript, because Rails itself aims to be an integrated framework. I don’t want to discuss whether we should minimize the amount of JS in our apps, but it’s inevitable: you <em>must</em> eventually write it in web apps, regardless of your strategy — and when you do it, you should <strong>use proper tools, keep concerns separated and test your code</strong>. And depending on the app, there’s no other way around: JavaScript is a given, especially these days where web applications have reached the plateau of interactivity.</p><p>I’ve seen apps with huge piles of spaghetti JavaScript that send shivers down the spine, where one doesn’t have the confidence to work with and constantly fears of all hell breaking loose. The only way to work with such a mess is to introduce hack on top of hack and avoid modifying any lines already working! That slows development down to a crawl because the code gets convoluted and hard to understand, and makes it easier to introduce bugs, regressions and decreases overall developer confidence.</p><p>Sprinkling code bits with RJS is a viable and popular alternative in the Rails community, but it’s frowned upon by many. When going with this strategy, the only reasonable way to test your JS code is by using end-to-end Capybara tests, which are slow and often unreliable — therefore they should be kept to a minimum.</p><p>You have to account for all paths a sprinkle of JS can take, which makes for a slow and bloated test suite that can eventually fail in weird ways. Or even worse, you end up not testing relevant code paths of your application. <strong>That’s not to say it’s an inherently bad approach — it can very well suit your needs</strong>! Everything in web development has pros and cons; you just have to weigh the best approach for your use case.</p><p>On the other hand, JavaScript unit and integration tests encourage proper modularity and run much faster and reliably than Capybara end-to-end suites any day. And they are also easy to write once you get the kicks, contrariwise to what many folks think! But you must do it while developing the code, or you might not have a chance to introduce tests without performing dangerous refactorings.</p><p>If you are serious about your application, your should have tests around any important business logic — it doesn’t matter whether written in a server-side language or something that compiles down to JavaScript.</p><h3>About our development process</h3><p>I really believe that TDD, when done right, can decrease the number of defects in any application. Here’s an outline of the process that we’ve been following:</p><ul><li>Write a short integration test describing a feature.</li><li>Let that test fail while the process is not over.</li><li>Figure out which units are required.</li><li>For each unit, write one spec example at a time and make it pass with a <strong>minimal</strong> change.</li><li>Repeat until the behavior of all units is completely covered.</li><li>Revisit the integration spec and make sure it passes.</li></ul><p>That’s no silver bullet, but nonetheless, it’s the first approach I consider when developing any feature. Its trick to high-quality code is<strong> doing a minimal change and adjusting after every new requirement or iteration. </strong>You can try to be too smart and write everything at once, and some experienced folks with a keen sense of modularity do it very well — but in some situations, the chance of getting bugs and uncovered edge cases tends to be higher.</p><p>And here’s something very cool which we’d not mentioned yet: we are test-driving our application without even opening the web browser! Fortunately, that will only be necessary once we get to the CSS part — we don’t need to do it while developing functionality, as long as we know what we are doing.</p><h3>Let’s build a parser</h3><p>So far, our application has been rendering an initial timeline when loading the web page for the first time, but it’s not exactly <em>presentable</em> to the end user and we’re not covering some important functionality:</p><ul><li>What if a tweet has newline characters? We certainly want to translate them to HTML tags such as paragraphs and line breaks.</li><li>What if a tweet contains mentions? We should wrap them within hyperlinks to make them navigable.</li></ul><p>Here’s how raw text comes out of the server:</p><pre>@john You seem to be missing something about Ruby versioning:\n\nMinor version bump, i.e. (2.3 -&gt; 2.4) can be backwards incompatible.\nGot it?</pre><p>But we want to present human-readable sentences:</p><pre>@john You seem to be missing something about Ruby versioning:</pre><pre>Minor version bump, i.e. (2.3 -&gt; 2.4) can be backwards incompatible.<br>Got it?</pre><p>Which translates into the following HTML markup:</p><pre>&lt;p&gt;&lt;a href=&quot;#&quot; data-mention&gt;@john&lt;/a&gt; This seems to be something many people miss about Ruby versioning&lt;p&gt;</pre><pre>&lt;p&gt;Minor version bump, i.e. (2.3 -&gt; 2.4) can be backwards incompatible.&lt;br&gt;Got it?&lt;/p&gt;</pre><blockquote>We can assume paragraphs are chunks of text delimited by two newlines, and single newlines correspond to line breaks.</blockquote><p>Every time you spot a series of transformations, you can think regarding a functional pipeline. Let’s imagine the flow of the raw text until getting to the final markup:</p><pre>sourceText |&gt; parseTweetMentions |&gt; wrapSentencesInTags |&gt; parseLineBreaks</pre><p>Each function of the pipeline performs a single transformation to the text and passes the result on to the next function, until spitting out a result.</p><p>Cool! We could start writing these functions immediately, but let’s get top-down as usual and specify an integration test.</p><h3>The integration test</h3><p>We need a function to orchestrate the interaction among the three smaller ones mentioned above. It will receive a raw tweet and return a brand new object with a parsed tweet.text. Let’s call it parseOneTweet.</p><p>Since this function is nothing more than a combination of three others, we can briefly describe it with an integration spec:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4df73624fa14219be6826d4ea36f147a/href">https://medium.com/media/4df73624fa14219be6826d4ea36f147a/href</a></iframe><p>As you can see, this spec has just enough to prove the orchestration works. We haven’t got the logic ready yet, so parseOneTweet will just return the input tweet for now:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/534ebcc1994badedfe119da6416fa13f/href">https://medium.com/media/534ebcc1994badedfe119da6416fa13f/href</a></iframe><p>And of course this spec fails, run it with npm run test:integration:</p><pre><strong>expected</strong> &#39;1 shot of Tequila</pre><pre>2 shots of Tequila...<br>3 shots of Tequila...&#39; <strong>to equal </strong>&#39;&lt;p&gt;&lt;a href=&quot;#&quot; data-js-mention&gt;<a href="http://twitter.com/dude">@dude</a>&lt;/a&gt; 1 shot of Tequila&lt;/p&gt;&lt;p&gt;2 shots of Tequila...&lt;br&gt;3 shots of Tequila...&lt;/p&gt;&#39;</pre><p>Excellent, now we can take care of the other functions and get deep down into each one’s behavior using unit tests.</p><h3>Wrapping sentences in paragraphs</h3><h4>When the text is blank</h4><p>The easiest way to get started with any unit test is by specifying the most trivial case: <em>the empty case</em>. When the text is blank and composed only of whitespace characters, we should expect wrapSentencesInTags to return an empty string:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1211ef495695921506844801b13ae437/href">https://medium.com/media/1211ef495695921506844801b13ae437/href</a></iframe><p>Since the spec does not depend on the browser environment, we can save it on the unit folder and run it as a “unit spec” with the following command:</p><pre>npm run test:unit</pre><p>Unfortunately, we get an error because we haven’t created the file yet:</p><pre>Module not found: Error: Cannot resolve module ‘app/twitter/wrapSentencesInTags’</pre><p>And to make it pass we can create the function and hardcode the return value:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/40a48f656b81175a1b2908e392e2acbf/href">https://medium.com/media/40a48f656b81175a1b2908e392e2acbf/href</a></iframe><h4>When having no newlines</h4><p>In that case, we expect the text to be trimmed and wrapped within <em>one</em> paragraph tag:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1b7f6cea56c7a4616c1494867028b180/href">https://medium.com/media/1b7f6cea56c7a4616c1494867028b180/href</a></iframe><p>It’s no surprise this spec fails: now our code needs to be good enough to make all examples pass. Some conditional string interpolation will do just fine:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fa74e1dad12eb1c7c3c2b42d7163a213/href">https://medium.com/media/fa74e1dad12eb1c7c3c2b42d7163a213/href</a></iframe><p>And here we are:</p><pre>wrapSentencesInTags<br> when source text is blank<br> ✓ renders an empty string<br> when source text does not have line breaks<br> ✓ is parsed to a paragraph with trimmed text</pre><h4>When having two chunks of text joined by two newlines</h4><p>In that case, we should have one paragraph for each chunk of text surrounding two newlines.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59e8df0cab580ad5a93ac3f39473931b/href">https://medium.com/media/59e8df0cab580ad5a93ac3f39473931b/href</a></iframe><p>Now we have to adjust the code so that it takes care of <em>many</em> paragraphs instead of just one:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b3c1d19dabcaae5e9066f436a120f34/href">https://medium.com/media/0b3c1d19dabcaae5e9066f436a120f34/href</a></iframe><p>This function makes everything pass, so far. It converts the string to an array of lines, trims all of them and conditionally wraps each one within a paragraph tag. In the end, it’s transformed back into a string.</p><h4>When having two chunks of text joined by three newlines</h4><p>Do you recall that a paragraph is any text delimited by two newlines? That said, we must leave any “single” newline characters alone:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1fb42ecda63ff1eb9320e9187e9128aa/href">https://medium.com/media/1fb42ecda63ff1eb9320e9187e9128aa/href</a></iframe><p>This spec yields the following error:</p><pre>AssertionError: <strong>expected</strong> &#39;&lt;p&gt;Hey!&lt;/p&gt;&lt;p&gt;Now we are talking&lt;/p&gt;&#39; <strong>to equal</strong> &#39;&lt;p&gt;Hey!&lt;/p&gt;&lt;p&gt;\nNow we are talking&lt;/p&gt;&#39;<br> + expected — actual</pre><pre>-&lt;p&gt;Hey!&lt;/p&gt;&lt;p&gt;Now we are talking&lt;/p&gt;<br>+&lt;p&gt;Hey!&lt;/p&gt;&lt;p&gt;<br>+Now we are talking&lt;/p&gt;</pre><p>It communicates we are chomping “single” newline characters when we shouldn’t.</p><p>Now things start to get tricky: our code has to satisfy <strong>four</strong> specs. We can make everything pass using a divide and conquer approach: first, trim all lines, then split the string by two newlines and apply the same paragraph transformation as before:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6cfb69b1f6737ae12c94ec4226d663f4/href">https://medium.com/media/6cfb69b1f6737ae12c94ec4226d663f4/href</a></iframe><p>Awesome, now we have four passing specs:</p><pre>wrapSentencesInTags<br> when source text is blank<br> ✓ renders an empty string<br> when source text does not have line breaks<br> ✓ is parsed to a trimmed paragraph<br> when source text has two chunks joined by two line breaks<br> ✓ chunks before and after are parsed to trimmed paragraphs<br> when source text has three subsequent line breaks<br> ✓ chunks before and after two line breaks are parsed to paragraphs</pre><h4>All cases together</h4><p>What if the raw text is bound to have <em>three</em> paragraphs? Let’s introduce a slightly more complex example, just to make sure the situation is parsed correctly:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0680eaefd173fafa22b520ae3c468b3c/href">https://medium.com/media/0680eaefd173fafa22b520ae3c468b3c/href</a></iframe><p>And it passes right away. This is just a safety net to make sure the code is dynamic and performs the same old transformation for each mention.</p><h4>Refactoring to a pipe</h4><p>The tests are passing, but the code’s still not good enough. Let’s refactor and make the flow more evident and explicit. If you quickly scan the function, you’ll notice it has two responsibilities: “trim lines” and “parse paragraphs”. Let’s extract them to specialized private functions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b34bf7a33d790e98a4425ef6ab2a6cb/href">https://medium.com/media/4b34bf7a33d790e98a4425ef6ab2a6cb/href</a></iframe><p>Wow, that’s a brutal difference! We named all concepts, and the code does not look like a hieroglyph anymore.</p><p>Next up, there’s a transformation going on within wrapSentencesInTags: the text goes through two functions at line 14, and it’s not exactly what I call <em>easy</em> to read.</p><p>lodash provides a pipe function to make these transformations explicit, which is part of its functional programming toolkit. Install lodash:</p><pre>$ npm install lodash --save</pre><p>Now we can build a new function by composing a “pipe” of two other functions:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7daa3bcfafb663ec84fa771f6939464c/href">https://medium.com/media/7daa3bcfafb663ec84fa771f6939464c/href</a></iframe><p>How awesome is that? The beauty of this approach is that we can add functions to the pipeline whenever we feel like needing new transformations.</p><h3>Replacing newlines with line breaks</h3><p>This is the most straightforward function of all three, so let’s not waste our precious time. Replacing \n with &lt;br&gt; yields the result we are aiming for. Here’s the spec:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b14c27a178180814a2942ff85b2130d/href">https://medium.com/media/0b14c27a178180814a2942ff85b2130d/href</a></iframe><p>And here’s how to make it green:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cb45a242e86988dc8c1ffc43ddbbde9c/href">https://medium.com/media/cb45a242e86988dc8c1ffc43ddbbde9c/href</a></iframe><h3>Parsing the mentions</h3><p>Do you recall that our API returns a list of mentions contained in each tweet? Here’s an (incomplete) JSON sample:</p><pre>{<br>  &quot;text&quot;: &quot;@dude Alright, I’ll be there. @yow get ready to rock&quot;,<br>  &quot;mentions&quot;: [&quot;dude&quot;, &quot;yow&quot;]<br>}</pre><p>We can use this list to figure out which mentions are in need of parsing. Searching and replacing all names that match a mention and skipping the list won’t do, because only Twitter knows which screen names are valid.</p><h4>The empty case</h4><p>What if a tweet has no text and consequently no mentions? Easy, it should return an empty string.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5889b6e5c802bea5fb9019bbb507aac4/href">https://medium.com/media/5889b6e5c802bea5fb9019bbb507aac4/href</a></iframe><p>Making this spec green is quite straightforward:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee23bb3f3ac2f76a1182ee186a1655b3/href">https://medium.com/media/ee23bb3f3ac2f76a1182ee186a1655b3/href</a></iframe><h4>A tweet with one mention</h4><p>Next up, a tweet can have one mention:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3520f11299f152de341558f8d9d2dedc/href">https://medium.com/media/3520f11299f152de341558f8d9d2dedc/href</a></iframe><p>To make this spec pass, we can build a dynamic “mention” regex and use it to replace a match with an HTML template:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/249241cb5c8268f96a1c848e86eb8fa3/href">https://medium.com/media/249241cb5c8268f96a1c848e86eb8fa3/href</a></iframe><h4>A tweet with two mentions</h4><p>What about two mentions? Does the code work for this case? Let’s see:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43eb08805f75f115b2a38ccf48d699b1/href">https://medium.com/media/43eb08805f75f115b2a38ccf48d699b1/href</a></iframe><p>Running this spec blows it all up, because we are currently taking care of just one mention:</p><pre>AssertionError: <strong>expected</strong> &#39;Released by &lt;a href=&quot;#&quot; data-js-mention&gt;<a href="http://twitter.com/dude">@dude</a>&lt;/a&gt; under <a href="http://twitter.com/yow">@yow</a> supervision’ <strong>to equal</strong> &#39;Released by &lt;a href=&quot;#&quot; data-js-mention&gt;<a href="http://twitter.com/d">@d</a>ude&lt;/a&gt; under &lt;a href=&quot;#&quot; data-js-mention&gt;<a href="http://twitter.com/yow">@yow</a>&lt;/a&gt; supervision&#39;</pre><p>Now we need to iterate over all mentions and repeat the same parsing procedure for each one:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/13635c61901f494604db3df14db18011/href">https://medium.com/media/13635c61901f494604db3df14db18011/href</a></iframe><h4>A tweet with the same mention twice</h4><p>Yeah, we haven’t considered this case up until now. The time has come to do so:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f14cb6203916e2b4b9ce5904279ec137/href">https://medium.com/media/f14cb6203916e2b4b9ce5904279ec137/href</a></iframe><p>We need to add a <em>global</em> modifier to the regex, so that it acts globally on the input text and replaces all occurrences. To make the failing spec pass, line 5 should now look like this:</p><pre>regexp = new RegExp(`@${m}\\b`, &#39;g&#39;);</pre><p>Bingo!</p><h4>When mention is surrounded by non whitespace on the right</h4><p>This is our first actual edge case. What if there’s something that could be mistaken as a mention but is not a mention?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa9fb4f81d66455c5242503575ae661f/href">https://medium.com/media/aa9fb4f81d66455c5242503575ae661f/href</a></iframe><p>This spec fails, but adding a “word boundary” character to the right of the regex makes it green. Change line 5 so that it looks like this:</p><pre>regexp = new RegExp(`@${m}\\b`, &#39;g&#39;);</pre><h4>When mention is surrounded by non whitespace on the left</h4><p>We haven’t yet covered the left border of the mention string. For instance, something like @prefix@dude should <em>not</em> be parsed as a mention:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6c9fd32e11ca0df8ea64c4b35f9b74a6/href">https://medium.com/media/6c9fd32e11ca0df8ea64c4b35f9b74a6/href</a></iframe><p>And this spec blows up!</p><pre>+ expected — actual</pre><pre>-&lt;a href=”#” data-js-mention&gt;<a href="http://twitter.com/dude">@dude</a>&lt;/a&gt; “<a href="http://twitter.com/prefix">@prefix</a>&lt;a href=”#” data-js-mention&gt;<a href="http://twitter.com/dude">@dude</a>&lt;/a&gt;” is not a valid ivar in Ruby<br> +&lt;a href=”#” data-js-mention&gt;<a href="http://twitter.com/dude">@dude</a>&lt;/a&gt; “<a href="http://twitter.com/prefix">@prefix</a>@dude” is not a valid ivar in Ruby</pre><p>Unfortunately, adding a word boundary to the left doesn’t work because @ is considered a “word” by regular expressions, which means the following regex is redundant and does not make sense: \b@dude\b. If we can’t count on word boundaries, we only have whitespaces left as an option.</p><p>Let’s make the pattern match either ^@${mention} at the beginning of a line or \s@${mention}\b, when anywhere else on the line. We must also add a whitespace to the left of the replacement template if it exists in the replacing mention. This code makes all cases pass:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6d86c8f771bc8b0bca74f3ebe2be77b3/href">https://medium.com/media/6d86c8f771bc8b0bca74f3ebe2be77b3/href</a></iframe><p>And that’s it for our specs, now normal and edge cases are covered!</p><pre>parseTweetMentions<br> with no mentions<br> ✓ returns an empty string<br> when having one mention<br> ✓ transforms the mention into an anchor tag<br> when having two mentions<br> ✓ transforms all mentions into anchor tags<br> when having the same mention twice<br> ✓ transforms both mentions into the same anchor tag<br> when a mention is surrounded by non whitespace chars on the left<br> ✓ is not parsed as a mention<br> when a mention is surrounded by non whitespace chars on the right<br> ✓ is not parsed as a mention</pre><p>Now we can proceed to refactoring.</p><h4>Refactoring to use reduce</h4><p>Let’s extract the code responsible for parsing <em>one</em> mention over to a private function. Remember: functions should do one thing and do it well.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b1ec918bdf7ffb9c98c5fb810685f08a/href">https://medium.com/media/b1ec918bdf7ffb9c98c5fb810685f08a/href</a></iframe><p>This refactor makes it clear that our business is all about reducing a collection of mentions into a string of text. Notice how we are accumulating the value of text at each iteration. Folks acquainted with functional programming will quickly perceive that we can use reduce to make the transformation explicit:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a8960f1bc6d1ca6f0c5123f9771ed47/href">https://medium.com/media/6a8960f1bc6d1ca6f0c5123f9771ed47/href</a></iframe><p>Specs still pass after performing this change, which means we are good!</p><h3>Back to the integration spec</h3><p>Now that all moving parts are working let’s unite them within parseOneTweet. We can compose a parser of three functions by using a pipe:</p><pre>pipe(parseTweetMentions, wrapSentencesInTags, parseLineBreaks)</pre><p>The order is really important here. parseTweetMentions reduces a full tweet object to a parsed string, and the other two functions receive a string. Also, we must parse paragraphs <em>before</em> parsing line breaks.</p><p>Moreover, we don’t want to mutate the tweet object, instead we want to create a new one: the only difference is it will hold a parsed text string instead of a raw one. Avoiding mutations is generally a good practice. Here is the final code with everything discussed until now:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/12933368ad45257218af0fb982bcf7e7/href">https://medium.com/media/12933368ad45257218af0fb982bcf7e7/href</a></iframe><p>And here’s the summary:</p><pre>parseOneTweet<br> ✓ returns a tweet object with parsed text</pre><h3>Plugging in the parser</h3><p>Now we need to plug our parser in the renderTweets function, which is responsible for transforming the API response into HTML markup. Note that renderTweets is not yet in an ideal spot — it still stands on the mountComponent function, but we will leave it as-is for now.</p><p>Adding a new transformation to the response does the trick:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7cc858cc67da6f78eb70ec3aa32764e9/href">https://medium.com/media/7cc858cc67da6f78eb70ec3aa32764e9/href</a></iframe><p>No process is perfect, especially in early stages where we don’t know all requirements upfront. We really expected our foremost integration spec (mountComponent.spec.js) to still pass after these changes, but it does not:</p><pre>1) renders an initial timeline<br> mountComponent<br> AssertionError: expected { &#39;0&#39;: &lt;p&gt;&lt;/p&gt;,<br> &#39;1&#39;: &lt;p&gt;Hi &lt;a href=&quot;#&quot; data-js-mention=&quot;&quot;&gt;<a href="http://twitter.com/dude">@dude</a>&lt;/a&gt;!&lt;/p&gt;,<br> &#39;2&#39;: &lt;p&gt;&lt;/p&gt;,<br> &#39;3&#39;: &lt;p&gt;&lt;/p&gt;,<br> &#39;4&#39;: &lt;p&gt;Pizza!&lt;/p&gt;,<br> &#39;5&#39;: &lt;p&gt;&lt;/p&gt;,<br> length: 6,<br> item: [Function: item] } to have a length of 2 but got 6</pre><p>This failure relates to the following expectation:</p><pre>expect(fixture.querySelectorAll(&#39;.tweet &gt; p&#39;)).to.have.length(2);</pre><p>We must have one paragraph for each tweet, thus summing it up to two — but instead we are getting six paragraphs! What’s going on?</p><p>Debugging techniques are beyond our scope here, but it turns out we’ve specified the renderOneTweet function with the assumption a tweet would only have one paragraph ever, which is currently hardcoded into the template. Let’s revisit that function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e175d7b99ae7d87213d819017a0f89d1/href">https://medium.com/media/e175d7b99ae7d87213d819017a0f89d1/href</a></iframe><p>For some reason, <em>webkit</em> browsers parse an HTML of two nested paragraphs (which is a syntax error) as three paragraphs— 2 tweets * 3 paragraphs == 6 actual paragraphs:</p><pre>&lt;p&gt;&lt;p&gt;Some text&lt;/p&gt;&lt;/p&gt;</pre><p>Since the tweet object comes into this function with paragraphs already rendered, we can now get rid of the hardcoded one. Just replace line 8 with this, and the integration spec will be all good:</p><pre>      ${tweet.text}</pre><h3>Fixing the last failing spec</h3><p>The previous tweak makes mountComponent.spec.js pass, but renderOneTweet.spec.js unit spec is now failing! Since it’s not the role of this function to render paragraphs anymore, we need to change line 12 from this:</p><pre>const tweet = { created_at: &#39;2016–01–01&#39;, text: &#39;Hi!&#39; };</pre><p>Into this:</p><pre>const tweet = { created_at: ‘2016–01–01’, text: &#39;&lt;p&gt;Hi!&lt;/p&gt;&#39; };</pre><p>And here’s the final spec:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/41ff9aa9be38055ac18ae53210483c43/href">https://medium.com/media/41ff9aa9be38055ac18ae53210483c43/href</a></iframe><p>And now everything is beautifully passing.</p><h3>Wrapping up</h3><p>I hope you have enjoyed this post. We won’t cover hashtags, emails and URLs, therefore you can probably build parsers for each of these items as an exercise. Once they’re ready, just plug them in the pipeline! And don’t forget to update the existing integration spec.</p><p>We are getting close to the end of this journey, but we still have a few posts coming up about <em>events</em> and other missing details. You may have noticed we didn’t mention JS <em>events</em> up until now; that’s because they are just simple declarations that hook up with existing code, so we deal with them in the end. And of course, we need to get back to our Capybara spec and add some CSS to prettify things for the end user as well.</p><p>You can find all the code developed here in <a href="https://github.com/thiagoa/twitter_widget/tree/the-frontend">this repository</a>.</p><p><em>The content has been quite dense; I mostly let the code speak for itself. If you have any questions, just hit me up in the comments! Thanks for reading.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a973a7b227f1" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeminer-42/go-full-stack-rails-the-frontend-part-3-a973a7b227f1">Go Full Stack Rails — The Frontend part 3</a> was originally published in <a href="https://medium.com/codeminer-42">The Miners</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go Full Stack Rails — The Frontend part 2]]></title>
            <link>https://medium.com/codeminer-42/go-full-stack-rails-the-frontend-part-2-e91ac08b40a?source=rss-84180f96c985------2</link>
            <guid isPermaLink="false">https://medium.com/p/e91ac08b40a</guid>
            <category><![CDATA[frontend]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Thiago Araújo Silva]]></dc:creator>
            <pubDate>Wed, 30 Nov 2016 15:54:11 GMT</pubDate>
            <atom:updated>2016-12-23T17:01:12.566Z</atom:updated>
            <content:encoded><![CDATA[<h4>About ES6 Promises and improving Promise-based specs</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mA7tqy6U9aabYfgqY38H6g.jpeg" /></figure><p>Welcome! Each part of this blog post series drills down into a bunch of pertinent details, aiming to form the big picture of a clean, maintainable and well-tested full-stack application written using Rails and ES6.</p><p>Although not strictly required, it might be helpful to catch up with previous episodes if you haven’t already:</p><ul><li><a href="https://blog.codeminer42.com/go-full-stack-rails-the-backend-a94b4d0e8897">The Backend Part 1</a>: Working on the backend, exploring requirements and building a Rails controller to deliver timeline tweets</li><li><a href="https://blog.codeminer42.com/go-full-stack-rails-the-backend-part-2-339db75a5db0">The Backend Part 2</a>: Building a timeline wrapper to isolate external dependencies</li><li><a href="https://blog.codeminer42.com/go-full-stack-rails-the-frontend-part-1-1b889c919b4a">The Frontend Part 1</a>: A brief introduction to test-driven frontend development</li></ul><h3>Where we left off</h3><p>In the last post, we went through some significant JS testing strategies and ended up with an integration spec describing <em>part</em> of our feature:</p><blockquote>When loading the web page for the first time, it should render tweets of a screen name which we call “initial timeline.”</blockquote><p>We turned that spec from red into green with no actual <em>logic — </em>instead, we made the mountComponent function return a hard-coded HTML string containing the tweets we expect. Obviously, this is not dynamic and thus is not what we want.</p><p>Also, the following requirements sprung out from that integration spec:</p><p>- Fetch timeline tweets from the server<br>- Render tweets on the screen</p><p>Which translates into the following line:</p><pre>fetchTimelineTweets(id).then(renderTweets);</pre><p>This code uses a modern JavaScript feature called “Promises.”</p><h3>Why promises?</h3><p>Promises are meant to alleviate the hassle of dealing with asynchronous code and avoid what is called “callback hell” or “callback soup.” In the old days, we’d probably have structured the example above like this:</p><pre>function fetchTimeline(id, callback) {<br>  $.ajax(&#39;/twitter/timeline/&#39; + id, { success: callback }); <br>}</pre><pre>fetchTimeline(id, function renderTweets(data) {<br>  // Code to parse and render incoming data<br>});</pre><p>Although not obvious, there are deep problems with this code. What if we wanted to trigger an asynchronous event <em>after</em> rendering? Call it from renderTweets. Want to trigger another event in the end? Ugh, nesting a function within the callback soup would be the go-to solution:</p><pre>fetchTimeline(id, function renderTweets(data) {<br>  // Code to parse and render incoming data</pre><pre>  triggerEvent(function someEvent(data) {<br>    triggerDependentEvent();<br>  });<br>});</pre><p>Can you visualize how this is bound to become a mess, even in a medium-sized application?</p><h4>Improving async code with Promises</h4><p>Promises were introduced natively in ES6 as a <em>construct</em> to improve this situation. With them, we can flatten any sequence of callbacks in a very clear layout:</p><pre>function fetchTimeline(id) {<br>  // Returns a promise object which resolves the request<br>  <br>  // Don&#39;t worry with the internal looks of a promise object,<br>  // instead focus on how to use them.<br>  // We&#39;ll get to that eventually.<br>}</pre><pre>const promise = fetchTimeline(id)<br> .then(renderTweets)<br> .then(triggerEvent)<br> .then(triggerDependentEvent);</pre><p>Furthermore, they provide an advantage: the caller can extend the promise <em>while it’s not resolved</em>. It’s worth noting: each callback along the chain obtains the return value of the previous one.</p><blockquote>Promises can attend a multitude of uses, so they’re not only useful to perform HTTP requests. ES6 has the tools to implement Promises around any kind of business logic.</blockquote><h4>Promises can also be rejected</h4><p>To handle rejections, we can pass a callback in to the catch function. It receives an <em>error</em> argument:</p><pre>function handleErrors(error) {<br>  // Handle the error somehow...<br>}</pre><pre>fetchTimeline(id).then(renderTweets).catch(handleErrors);</pre><p>Basically, catch callbacks are used to:</p><ul><li>Handle rejections and ignore then callbacks.</li><li>Catch <strong>exceptions</strong> thrown from previous then callbacks.</li></ul><blockquote><strong>Note</strong>: To catch exceptions originated in the promise “core” itself, use a <em>then(successCallback, errorCallback)</em> signature.</blockquote><p>It’s also possible to re-throw the error should we want to propagate it over the call stack:</p><pre>function handleErrors(exception) {<br>  // Handle the exception and…<br>  <br>  throw exception;<br>}</pre><pre>fetchTimeline(id).then(renderTweets).catch(handleErrors);</pre><p>Now we know just enough about promises to get going, but before that let’s take a look at some workflow tips.</p><h3>Tips for running specs smoothly</h3><p><a href="https://github.com/codeminer42/code42template">code42template</a> provides some useful shortcuts to help us run specs. The following command watches for changes in project files and runs integration specs automatically and continuously:</p><pre>$ npm run test:integration:watch</pre><p>That’s especially useful when keeping two windows or split panes opened side-by-side: one with the code editor and another with the test runner.</p><p>You can also run one spec at a time and skip the rest. Just chain the only attribute after the it function:</p><pre>it.only(&#39;does stuff&#39;, () =&gt; {<br>  // Your test here<br>});</pre><p>You can leverage the same trick with context or describe:</p><pre>context.only(&#39;a group of examples&#39;, () =&gt; {<br>  // Focus on all examples of this context<br>});</pre><p>Keep in mind that only should be used temporarily, so don’t ever commit it in version control!</p><h3>Fetching timeline tweets</h3><p>What would be the ideal implementation for fetchTimeline? It should probably return a promise object which eventually resolves into a response body. The caller could then extend it with then and catch callbacks.</p><p>We will use the <em>axios</em> library, a standalone, promise-driven HTTP client which smooths out dealing with low level XMLHttpRequest APIs.</p><blockquote>Why not jQuery? Its famous “ajax” method is promise-compliant, but we would be bringing over a whole jungle of unneeded features.</blockquote><h4>When the timeline response is 👍</h4><p>A sensible strategy to test fetchTimeline‘s behavior in isolation is to stub out integration boundaries such as the HTTP layer. We can use <em>sinon fake server</em> to accomplish that.</p><p>Let’s make sure fetchTimeline’s return value is promise-compliant and whether it’s able to use a then callback:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/90b57c3089e0731bd6bb6983499ba26c/href">https://medium.com/media/90b57c3089e0731bd6bb6983499ba26c/href</a></iframe><blockquote>Technically this is a <strong>unit</strong> test. It’s stored in the “integration” folder because it needs to interact with browser-specific features such as AJAX.</blockquote><p>In a nutshell, this spec makes sure that:</p><ul><li>The request resolves to the correct response body</li><li>Only then callbacks are called</li></ul><p>Other than that, three aspects especially draw our attention here:</p><ul><li><em>Mocha</em> <strong>waits</strong> until the promise returned from the example resolves. This allows performing assertions at the tail of the callback chain, thus avoiding messy workarounds such as setTimeout. Remember to return the promise if you want this behavior.</li><li>We are using <em>sinon fake server’s</em> autoRespond feature. It makes the request respond as soon as possible and avoids manual calls to server.respond().</li><li>The deep.equal expectation tells mocha to compare each nested member recursively. Had we used equal, our spec would have failed due to that assertion being shallow.</li></ul><p>All good, now let’s make this boy pass.</p><h4>Making this spec pass</h4><p>Run the spec and you’ll see the following error in your terminal:</p><pre>fetchTimeline<br> when timeline response is ok<br> ✗ runs only then callback<br> Can’t find variable: fetchTimeline</pre><p>Let’s introduce the function that the error is asking for. Firstly, import it at the top of the spec file:</p><pre>import fetchTimeline from &#39;app/twitter/fetchTimeline&#39;;</pre><p>Now we need to install the <em>axios</em> library. Run the following command in your terminal:</p><pre>npm install axios --save</pre><p>Finally, let’s implement the actual code. Our implementation starts out very simple:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/da2d907350f3ad803946b4473f986718/href">https://medium.com/media/da2d907350f3ad803946b4473f986718/href</a></iframe><p>But the following error pops up after running the spec:</p><pre>fetchTimeline<br> when timeline response is ok<br> ✗ runs only then callback<br> expected { Object (data, status, …) } to deeply equal { tweets: [ { text: ‘Hi!’ } ] }</pre><p>This message is quite confusing, but if you play around with <em>axios</em> for a while or take a look at its <a href="https://github.com/mzabriskie/axios">README</a>, you may notice that get returns a <strong>full</strong> response object.</p><p>We are only interested in the response body, so we need to filter it out before returning the promise. Here’s how to do that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87aafb0d7092d8171dbd011972442514/href">https://medium.com/media/87aafb0d7092d8171dbd011972442514/href</a></iframe><p>And now our spec passes!</p><pre>fetchTimeline<br> when timeline response is ok<br> ✓ runs only then callback</pre><h4>Chaining “then” callbacks</h4><p>The next example is fairly straightforward. Let’s make sure our promise object is able to chain then functions and transmit return values from callback to callback:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/18a4efdad576e4a4daf917255058a205/href">https://medium.com/media/18a4efdad576e4a4daf917255058a205/href</a></iframe><p>The first expect call is a “smoke” precaution to avoid weird failures in case we receive something unexpected from the promise. The second expect actually meets our goal, and uses the tweet text to transmit a “modified” return value through the chain.</p><p>You are probably noticing: this is starting to get hairy! Why are we going through all this trouble to test an HTTP promise? Let’s improve this thing and make our point clearer, starting with some sensible DRY improvements.</p><h3>Refactoring our test</h3><p>This is the most entertaining part of the process. Looking at what we currently have, the code to perform an HTTP request is particularly repetitive and annoying.</p><p>Let’s make good use of JavaScript by leveraging its dynamism the right way! Why not extract a helper method to return an “extended” fake server object?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8200ae116f8482d33a6045bb2d61f345/href">https://medium.com/media/8200ae116f8482d33a6045bb2d61f345/href</a></iframe><p>Notice how we are extending the object with a new member function that’s especially suited for what we need. Now we can apply the helper to all of our examples:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dd14a039907d0ae7ea03223856222aee/href">https://medium.com/media/dd14a039907d0ae7ea03223856222aee/href</a></iframe><p>That’s a bit better, but we can improve it even further with a promise assertion plugin.</p><h4>Using chai-as-expected to improve promise assertions</h4><p>In the end, a promise resolves to the value returned by its last callback, right? <a href="https://github.com/mzabriskie/axios">chai-as-expected</a> allows us to turn this:</p><pre>return promise.then((body) =&gt; {<br>  expect(body).to.deep.equal(response);<br>});</pre><p>Into this:</p><pre>return expect(promise).to.eventually.equal(response);</pre><p>How does it work? Chaining the eventually attribute before any existing <em>chai</em> expectation has the effect of “promisifying” it. Furthermore, <em>mocha</em> automatically <strong>waits</strong> for returned promises, remember that?</p><p>Now let’s install the plugin as an NPM <em>dev</em> dependency:</p><pre>npm install chai-as-expected --save-dev</pre><p>We need to tell <em>chai</em> about this new plugin. Edit spec/javascripts/index.integration.js, so that it looks like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/81e378ee4cbecf1b285403bef7a28f71/href">https://medium.com/media/81e378ee4cbecf1b285403bef7a28f71/href</a></iframe><p>Great. Now we can refactor our spec:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f9087cd6990bb9c3fc77bebac0619e39/href">https://medium.com/media/f9087cd6990bb9c3fc77bebac0619e39/href</a></iframe><p>Hola! That’s a bit better and easier to read. Now let’s tackle the last context of this spec.</p><h4>When the timeline response is 👎</h4><p>And what if we eventually get a non-200 HTTP response? Well, the catch callback should be fired with an error object, including at least the HTTP status code and the body.</p><p>Fortunately, <em>axios</em> implements that behavior out of the box and our example gets pretty straightforward:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/092674e8873742fd28ddf38778ad6f5a/href">https://medium.com/media/092674e8873742fd28ddf38778ad6f5a/href</a></iframe><p>And it passes right away.</p><p>For sanity’s sake, I suggest you to change the expected value and check if anything fails. A spec that passes right on the first run should be faced as a smell, it doesn’t matter whether testing before or after the implementation!</p><p>And we are finally done with fetchTimeline!</p><h4>But hasn’t a promise more features than this?</h4><p>Yeah, a promise has other behaviors. However, that’s just enough to secure our implementation and provide confidence that it works correctly, taking into account the features we will actually use.</p><h4>Why is this a good test?</h4><p>Astute readers will probably ask:</p><blockquote><em>Couldn’t we have used stubs to test this?</em></blockquote><p>Yes, but that would probably be a bad move. I really like using stubs when it makes sense, but in some cases they couple too much with the implementation and make things harder to change. Focusing on <strong>actual behavior</strong> is always a better bet.</p><p>The advantage of the current approach is that we can switch out the HTTP code to use any promise-compliant library. Now here’s what’s downright cool: the following <em>jQuery</em> code has the same behavior and would still make our specs pass:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0bd9174e7e1e9a2938a36e213cfbe47b/href">https://medium.com/media/0bd9174e7e1e9a2938a36e213cfbe47b/href</a></iframe><p>Of course, we don’t want this code, but watch this: we will share specs between both implementations, just for fun and to make sure they behave exactly the same:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2511acd8cf0cbd4add83fa0776f292f/href">https://medium.com/media/f2511acd8cf0cbd4add83fa0776f292f/href</a></iframe><p>I hope this gives you a good taste of using shared examples with <em>mocha</em>. It’s just <em>JavaScript</em>™.</p><h3>Rendering tweets</h3><p>Finally, here’s the “connection” we are striving for:</p><pre>fetchTimelineTweets(id).then(renderTweets);</pre><p>Since we want single purpose functions, let’s build one to render an individual tweet. We can then use map to act on a collection.</p><h4>Rendering one tweet</h4><p>This function is dead simple. It receives a tweet object with created_at and text members and returns the corresponding HTML template. Let’s enumerate the steps to test this:</p><ol><li>Call the renderTweet function with a tweet object.</li><li>Inject the returned HTML into the DOM as a fixture.</li><li>Query the DOM and make sure that what’s expected is there.</li></ol><p>Cool! Here’s how might we go about this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/36425c1cbebecf2ff119298dd270a055/href">https://medium.com/media/36425c1cbebecf2ff119298dd270a055/href</a></iframe><p>And to make this spec pass, we can use some straightforward ES6 interpolation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e175d7b99ae7d87213d819017a0f89d1/href">https://medium.com/media/e175d7b99ae7d87213d819017a0f89d1/href</a></iframe><p>And that’s it!</p><p>We could have used a <em>templating</em> library, but let’s keep it simple for now. After all, we trust Twitter not to deliver anything stupid security-wise, right?</p><h3>Make that integration spec pass</h3><p>Do you recall that integration spec which kicked off everything, showed off in the last post? Let’s make it pass with the functions we currently have.</p><p>Before that, let’s use our new createFakeServer helper to DRY it up:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9e6df6bcd870425e75bb7762e60ea5a/href">https://medium.com/media/b9e6df6bcd870425e75bb7762e60ea5a/href</a></iframe><p>Now let’s remove the hard-coded HTML markup and make the spec pass with <strong>dynamic</strong> code. We are still lacking the renderTweets function, so let’s implement it within mountComponent:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fb113676601bf7668ceed5114b21026f/href">https://medium.com/media/fb113676601bf7668ceed5114b21026f/href</a></iframe><p>Awesome, now our code is working as it should! Rejoice at the spec output:</p><pre>fetchTimeline<br> when timeline response is ok<br>   ✓ runs only then callback<br>   ✓ chains then callbacks<br> when timeline response is not ok<br>   ✓ runs only the catch callback</pre><pre>mountComponent<br>  ✓ renders an initial timeline</pre><pre>renderOneTweet<br>  ✓ transforms a tweet object into an HTML string</pre><p>But didn’t we say in the last post that mountComponent should hold no actual <em>logic</em>? Yeah, that’s right in <a href="https://blog.codeminer42.com/go-full-stack-rails-the-frontend-part-1-1b889c919b4a#93f9">Coding Conventions</a>! renderTweets will be moved to somewhere else in the future. Our concern is only about making the spec pass, and refactoring comes after that :)</p><h3>To be continued…</h3><p>There’s still ground to cover about Promises, as well as features to refactor and develop. We will learn how to construct our own Promises with ES6 and make good use of that in our specs.</p><p>Developing a similar app is easy once you get to know all of this stuff. Practice is key: play around with examples, break stuff intentionally, try to build apps on your own. It takes a lot of practice to acquire proficiency in JavaScript development and testing. All the code developed up until now can be found in <a href="https://github.com/thiagoa/twitter_widget/tree/the-frontend">this GitHub repository</a>.</p><p>All that said, happy hacking and see you soon!</p><p><em>If you have any questions or cool approaches to go about the stuff herein, do me a favor and hit me up in the comments!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e91ac08b40a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeminer-42/go-full-stack-rails-the-frontend-part-2-e91ac08b40a">Go Full Stack Rails — The Frontend part 2</a> was originally published in <a href="https://medium.com/codeminer-42">The Miners</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go Full Stack Rails: The Frontend part 1]]></title>
            <link>https://medium.com/codeminer-42/go-full-stack-rails-the-frontend-part-1-1b889c919b4a?source=rss-84180f96c985------2</link>
            <guid isPermaLink="false">https://medium.com/p/1b889c919b4a</guid>
            <category><![CDATA[testing]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Thiago Araújo Silva]]></dc:creator>
            <pubDate>Mon, 07 Nov 2016 16:02:04 GMT</pubDate>
            <atom:updated>2017-07-06T10:34:25.891Z</atom:updated>
            <content:encoded><![CDATA[<h4>A brief introduction to test-driven frontend development</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Rxzsy_E2MgxPP5oVmh1Q_g.jpeg" /></figure><p>In “The Backend” <a href="https://blog.codeminer42.com/go-full-stack-rails-the-backend-a94b4d0e8897">part 1</a> and <a href="https://blog.codeminer42.com/go-full-stack-rails-the-backend-part-2-339db75a5db0">part 2</a> we pondered over the design of an endpoint to serve timeline tweets to a frontend client. In this post, we will resume our full-stack journey and start implementing the code to consume and present those tweets, and it will be written in ES6 JavaScript.</p><p>You may be curious about which framework we’ve chosen to power our application: is it React, Angular, Vue, Backbone, Ember, or another one? We <em>must</em> use a framework, right? It usually takes time to come up with an answer to this question, but I already have one: React is an excellent view framework and would be the choice of most modern <em>JavaScripters</em> out there, but let us take a different direction here.</p><p>It turns out that what we need to accomplish is quite simple, and given our requirements we <strong>don’t need</strong> the weight of a framework — it would probably be overkill! Furthermore, I don’t want to burden the reader with too many concepts at once — our focus shall be directed towards the JavaScript language and its raw power.</p><p>For this simple app, I find it much more valuable to use the organizational features provided by ES6 together with some small utility libraries. That said, we will come up with a simple and straightforward organization scheme and follow a few sensible conventions to guide our way.</p><p>By the way, have you ever wondered about which problems a framework like React solves for you? The best way to find out is to experiment and properly build apps <em>without</em> <em>any frameworks</em>. Chances are you won’t find their additional baggage and/or complexity worth in a lot of cases! Moreover, you will learn the essential technologies powering the JavaScript ecosystem.</p><p>Even though some frameworks force you to turn your app into an SPA, there is no need to do that without a strong reason involved in the decision — and with having Rails at our disposal, our app can become a healthy mixture of server-side rendered pages and JavaScript components. By properly breaking up our frontend logic we can achieve an abstraction much akin to a “<em>component</em>”.</p><p>For this part of the tutorial, I expect you to be acquainted with the basics of JavaScript and ES6. Now let’s move on and take a look at the aforementioned conventions.</p><h3>Our coding conventions</h3><p>I’ve come up with <em>three</em> simple conventions as part of this exercise:</p><h4>Stick with simple functions unless a class makes sense</h4><p>JavaScript is a different kind of object oriented language and its most powerful building block is the <em>function</em>. You will be surprised to acknowledge that we hardly need the shape of “classic” objects on this application. Our functions should aim to be highly specialized and strive to do one thing only.</p><pre>export default function singlePurposeFunction() {<br>  # my code here<br>}</pre><h4>Use a bootstrap file to mount components</h4><p>A bootstrap file is any file meant to <em>initialize</em> an application or part of its functionality, much like C’s “main” function.</p><p>Our <em>Twitter Timeline </em>component will provide a “mounter” function and readability will be its main selling feature: programmers who read this file will have a <em>high-level</em> overview of everything the component does, in just a few lines of code. The body will contain no logic whatsoever, just function calls and some glue code where needed.</p><pre>export default function mountComponent() {<br>  executeStep1();<br>  executeStep2();</pre><pre>  bindSomeEvent();</pre><pre>  # other readable, high-level steps<br>}</pre><p>We should never let this file grow out of bounds, for it would be a sign that the mounter is doing <em>more</em> than it’s supposed to do — which suggests the introduction of new abstractions.</p><h4>Reference DOM nodes only within the bootstrap file</h4><p>Functions should not hard code any DOM nodes; preferably, these nodes should come in as arguments of the mountComponent function — which in turn should delegate them down to other smaller functions.</p><p>The goal is to make code decoupled and reusable, which also provides nice side effects on tests. Small measures such as these are generally beneficial in the long run in order to keep a healthy system.</p><h3>About JavaScript specs</h3><p>The <a href="https://github.com/codeminer42/code42template">code42template</a> application generator uses <a href="https://mochajs.org/">mocha</a> as its JS test framework and <a href="https://karma-runner.github.io/">karma</a> + <a href="http://phantomjs.org/">PhantomJS</a> as its test runner.</p><blockquote>You might recall from our first post that we generated the skeleton of our Twitter-based application using code42template. <a href="https://github.com/codeminer42/code42template">Check it out</a> if you haven’t already!</blockquote><p>PhantomJS is a headless browser; in our case it provides a full-fledged environment upon which to run integration specs. How does the mocha + PhantomJS combo work? The test environment starts out with a bare HTML document including the mocha.js script tag, a naked <em>body</em> tag and some code to trigger the execution of found spec examples. That said, it’s not a good idea to rely on any global state in your specs because the environment only boots up once.</p><p>First and foremost, let’s aim to write an integration spec for our Twitter-based app. JS integration specs are <em>slightly</em> similar to <a href="https://github.com/jnicklas/capybara">Capybara</a> end-to-end specs, but they are isolated from the backend and thus run much faster and reliably than the former. What does that mean? It means our application is conceptually decoupled from the server and can be mounted anywhere, as long as a minimal skeleton template is provided in the HTML.</p><p>Before delving into our app, let’s learn how to write an integration spec.</p><h4>The outline of a frontend integration spec</h4><p>Every mocha spec follows an outline that is similar to the following:</p><ul><li>Describe a subject using a describe function.</li><li>Declare shared setup variables at the top of the describe function.</li><li>Initialize shared setup using a beforeEach function.</li><li>Tear down shared setup using an afterEach function.</li><li>Have any number of examples in as many it functions as needed.</li></ul><blockquote>The setup steps are optional. I recommend using them to share environment configuration required by all spec examples.</blockquote><h4>Show me some code!</h4><p>Imagine we want to test a function that receives the price of some cart items and renders the total price on the screen. This function is naturally “integrated”, since it deals with two responsibilities and one of them is intrinsic to the browser environment: calculate a total price and <em>render it out on the screen</em>. For this reason, it’s a great candidate to be exercised by an integrated test.</p><p>What is the goal of this spec? We simply want to assert that the total price gets correctly displayed in a DOM node of our choice upon calling the subject function.</p><p>Without further ado, here’s the spec code:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a3539f4a584ea61972c369983fd5d3e3/href">https://medium.com/media/a3539f4a584ea61972c369983fd5d3e3/href</a></iframe><p>Three aspects are specially noteworthy here:</p><ul><li>The shared setup scheme creates and destroys DOM nodes around every example. We call these special nodes “<em>fixtures”</em>.</li><li>createFixture is a small in-house function responsible for creating a fixture <em>div</em> tag into the DOM tree with any custom HTML we want.</li><li>We are using the <a href="http://chaijs.com/api/bdd/">chai BDD expect interface</a> to obtain a syntax very similar to <em>RSpec’s. </em>It needs to be explicitly imported in every spec file.</li></ul><blockquote>Watch out: <strong>the DOM is global!</strong> If you ever forget to clean it up, other specs onward may get in deep trouble! Removing the fixture node altogether provides a clean environment for subsequent specs to run upon.</blockquote><p>Now let’s see what our spec looks like in action! First of all, we need to define a createFixture helper method to be used by the spec. Create the following file at the pointed out location:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/315e286f5eba6515ac387bcef4c922b6/href">https://medium.com/media/315e286f5eba6515ac387bcef4c922b6/href</a></iframe><p>As you can see, this file holds no mystery; it uses the global document object provided by the browser environment to create <strong>and</strong> insert the fixture node into the DOM tree. It also defines a destroy function dynamically as a property of the fixture object, so that it’s easier to destroy the fixture at the <em>teardown</em> step.</p><p>Now copy the spec file over to spec/javascripts/integration/example.spec.js and run it:</p><pre>$ npm run test:integration</pre><p>The resulting output might look slightly polluted until you get used to it, but scroll up a little bit and you will see the following error message:</p><pre>1) calculates and displays the cart total<br> renderCartTotal<br> Can’t find variable: renderCartTotal</pre><p>That means we need to implement a renderCartTotal function. Write the following code at the top of the spec file, after the import statements:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fc8c5b457e4511a941325a0d37fedab7/href">https://medium.com/media/fc8c5b457e4511a941325a0d37fedab7/href</a></iframe><p>Now run the spec again and rejoice!</p><pre>renderCartTotal<br> ✓ calculates and displays the cart total</pre><p>That’s awesome! We now have a working JavaScript spec, and despite its “integrated” nature it was quite easy to write!</p><h3>Our first actual integration spec</h3><p>It’s time to get back to our app and work on its first integration spec.</p><p>Before doing that, I’d like to introduce you to <a href="http://sinonjs.org/">sinon</a>: a popular mocking/stubbing swiss army-knife which comes baked into <em>code42template</em>. And not only that: the <em>sinon</em> project provides a very cool feature: the <em>fake server</em>. Let’s learn what it is and where we can use it.</p><h4>The sinon fake server</h4><p><em>Sinon</em> <em>Fake Server</em> works by stubbing out the native <em>XMLHttpRequest</em> JavaScript APIs, so that it’s possible to simulate AJAX requests and make them return “canned” responses. Since every third-party HTTP client library must go through this lower level API, <em>fake server</em> should automatically work with all of them! Examples of third-parties are jQuery’s <a href="http://api.jquery.com/jquery.ajax/">ajax</a> method and the standalone <a href="https://github.com/mzabriskie/axios">axios</a> library.</p><p>Using <em>fake server</em> is simple: provide the request and response details, trigger it out, and the canned response will kick in once a matching request gets performed anywhere in the application:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ae4a0037d36e2f7d988edd20903f1ba3/href">https://medium.com/media/ae4a0037d36e2f7d988edd20903f1ba3/href</a></iframe><p>It’s worth noting that AJAX requests are asynchronous, and with <em>sinon</em> we can respond to them whenever we want.</p><p>On the example above we assume that performRequest() performs a <em>non-blocking</em> AJAX request behind the curtains, which means that while other code executes, the request keeps on waiting until a response arrives, then it handles the response asynchronously using a callback. When using <em>sinon fake server</em>, it’s mandatory to manually trigger the response using server.respond().</p><h4>Onto the code</h4><p>As noted in <a href="https://medium.com/@thiagoaraujos/go-full-stack-rails-the-frontend-part-1-1b889c919b4a">part 1</a>, our application needs to render a default timeline upon initialization. The first step in that direction is to write a full integration spec describing part of the feature. How might we do that?</p><p>As you may have already guessed, we need to stub out the timeline endpoint developed in <a href="https://blog.codeminer42.com/go-full-stack-rails-the-backend-a94b4d0e8897">part 1</a> using the <em>fake server</em>. We’ll do that by simulating a response with two tweets and an “ok” status, and in the end we’ll assert whether the DOM has the right contents. Seems easy enough, huh?</p><p>For now, it makes a lot of sense for each tweet to have the following HTML structure:</p><pre>&lt;div class=&quot;tweet&quot;&gt;&lt;p&gt;Hey there!&lt;/p&gt;&lt;/div&gt;</pre><blockquote>There are other elements to a tweet such as “date” and “mentions”, but let’s not worry with them right now. Notwithstanding, our fake response will still contain all of them and we shall fill these gaps in the upcoming posts!</blockquote><p>Hopefully, the following spec will look familiar to you:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8ccbfb38e8e82ce40189a0c21dedc252/href">https://medium.com/media/8ccbfb38e8e82ce40189a0c21dedc252/href</a></iframe><p>Basically, here’s what this spec does:</p><ul><li>Injects the HTML fixture into the DOM tree.</li><li>Instantiates a <em>fake server.</em></li><li>Simulates a request to the twitter_timeline/thiagoaraujos endpoint and makes it receive a fake response matching the format of the real backend.</li><li>Mounts the component: it’s assumed that mountComponent performs an AJAX request internally and the request’s callback uses the response to render tweets on the screen.</li><li>Triggers server.respond(), thus delivering the fake response over to the request’s callback.</li><li>Selects all tweets from the DOM using the global <em>document</em> object and runs expectations on their length and text.</li></ul><p>But why are we using setTimeout? Good question! Do you recall that AJAX requests are asynchronous? So, that’s exactly the reason why we are going through this trouble. We must wait until the request’s bound callback receives and renders out the response.</p><p>Also, notice the done parameter at the it function’s signature... what does it even mean? Unfortunately, it returns before setTimeout starts running, but with done we can trick mocha into waiting for our signal. Its optional presence means: “<em>hey mocha, there’s some asynchronous code in this example, but </em><strong><em>wait</em></strong><em> until I tell you it’s finished running!</em>”. And by <em>calling</em> done() we are saying: “<em>hey mocha, my async code is over and my assertions have been run, now go ahead and gather the spec results!</em>”.</p><blockquote>In the next posts we will refactor the code to not use setTimeout, which seems like a smell.</blockquote><p>And what if we hadn’t call done()? In that case, the spec would have timed out after 2 seconds!</p><p>On the other hand, the <strong>complete absence</strong> of a done callback would have told mocha that results can be “gathered” as soon as the it function returns. Had we not used it, mocha would have assumed the example’s completion b<em>efore </em>any assertion had run, which means our spec would have erroneously passed with 0 expectations.</p><p>Let’s get back on track and run the spec with npm run test:integration. You’ll see the following error message after that:</p><pre>Can’t find variable: mountComponent</pre><p>It seems pretty obvious, let’s create a “naked” mountComponent function at the pointed out location:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4111d6b84e6a180ec2c5675e8086deca/href">https://medium.com/media/4111d6b84e6a180ec2c5675e8086deca/href</a></iframe><p>And finally, we need to import the mountComponent function into the spec. Add the following line at the top of the spec file, below the other import statements:</p><pre> import mountComponent from &#39;app/twitter/mountComponent&#39;;</pre><p>After running the spec again a new kind of error pops up:</p><pre>expected { length: 0, item: [Function: item] } to have a length of 2 but got 0</pre><p>Awesome, that’s our first actual spec failure — it means there are no tweets rendered after running the code, which is correct! We can make it pass <strong>right away</strong> by introducing the following code in the <em>mountComponent</em> function:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3761c22261fe820de3c7a8871b9a303/href">https://medium.com/media/f3761c22261fe820de3c7a8871b9a303/href</a></iframe><pre>mountComponent<br>    ✓ renders an initial timeline</pre><h4>What’s next?</h4><p>OK, this is probably a <em>silly</em> way to make the spec pass, but at least it will remain green until we need to take the next big step, which is when we’ll get back to this code again! Most importantly, it forces us to reflect about what comes next:</p><ul><li>Fetch timeline tweets from the server</li><li>Render tweets on the screen</li></ul><p>How beautiful would our code look like if it had the following appearance?</p><pre>fetchTimelineTweets(id).then(renderTweets);</pre><p>The actual code won’t look <em>exactly</em> like this, but it seems like a great idea to try and improve upon! It’s beneficial to plant in ourselves the ability to imagine how code will look like beforehand; if it’s not clean or readable enough or if it does not fit into the requirements, it can probably be improved.</p><h3>Wrap up… for now</h3><p>This introduction focused a lot on the basics and hadn’t really a lot of code other than specs. Nevertheless, I hope you have enjoyed it!</p><p>In the next post we will continue our journey and work on smaller functions that’ll make our spec pass <em>for real</em>, and also introduce you to some libraries and modern JavaScripts concepts such as promises.</p><p>Until then, happy hacking!</p><p><em>If you have any questions or suggestions just hit me up in the comments!</em></p><p><em>Thanks to </em><a href="http://twitter.com/talyssonoc"><em>@talyssonoc</em></a><em> for having a second eye on this post!</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1b889c919b4a" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeminer-42/go-full-stack-rails-the-frontend-part-1-1b889c919b4a">Go Full Stack Rails: The Frontend part 1</a> was originally published in <a href="https://medium.com/codeminer-42">The Miners</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Go Full Stack Rails: The Backend part 2]]></title>
            <link>https://medium.com/codeminer-42/go-full-stack-rails-the-backend-part-2-339db75a5db0?source=rss-84180f96c985------2</link>
            <guid isPermaLink="false">https://medium.com/p/339db75a5db0</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Thiago Araújo Silva]]></dc:creator>
            <pubDate>Thu, 20 Oct 2016 14:23:22 GMT</pubDate>
            <atom:updated>2016-10-31T10:23:33.782Z</atom:updated>
            <content:encoded><![CDATA[<h4>Building a timeline wrapper to isolate external dependencies</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AAu3toQHqK7IIIrTdAqHBA.jpeg" /><figcaption>Some chocolate candy wrappers</figcaption></figure><p>Welcome! This series of blog posts is an endeavor where I walk the reader through building a real, albeit small full-stack application with Rails and ES6. There are no cute or purposefully made-up or contrived examples to aid in blogging, here you get the raw and real deal! If you haven’t yet, <a href="https://blog.codeminer42.com/go-full-stack-rails-the-backend-a94b4d0e8897">read part 1</a>.</p><p>In our first post we thoroughly explored the requirements needed to build a Twitter-based application, and also created a feature spec and a Rails controller to deliver timeline tweets over to our yet-to-be-created frontend client.</p><p>As you might remember, we imagined our controller’s one and only dependency using the <a href="http://blog.adrianbolboaca.ro/2016/04/programming-by-wishful-thinking/">programming by wishful thinking</a> technique, and even stubbed it out in our controller spec without it even existing! That dependency is a class which wraps the Twitter gem’s timeline retrieval mechanism and delivers the result in a format our application can easily consume.</p><p>Our controller spec is using a canned timeline response due to our planning ahead of dependency inputs and outputs, which allowed us to create and test our controller totally in isolation. Here’s the planned interface for the wrapper:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ab74699be3d608720a6c0b78f466a89/href">https://medium.com/media/0ab74699be3d608720a6c0b78f466a89/href</a></iframe><p>The <em>result</em> variable ought to be an instance of the following Struct:</p><pre># Status can be one of: ok, not_found or forbidden<br>Struct.new(:status, :tweets)</pre><p>Technically, our wrapper is a kind of <a href="https://en.wikipedia.org/wiki/Facade_pattern">facade</a>: it reduces dependencies of outside code and avoids them to spread throughout our Rails codebase. That means our application interacts directly with the facade instead of with the gem’s third party code, and most importantly: our facade simplifies and fixes fundamental design mistakes with the Twitter gem; this will become evident later on this post.</p><p>As we are going top-down all the way, we’ll start by determining the dependencies <em>TwitterTimelineHub</em> itself needs.</p><h4>The Twitter client factory</h4><p>We need to forge a specialized class to hold knowledge about <em>how</em> to create a ready-to-use Twitter client. The reason is simple:</p><ul><li>Configuring a client is a repetitive process that could be abstracted away by a factory.</li><li>Our wrapper needs to have a default <em>twitter_client</em> in case none is specified. It should accept an optional <em>twitter_client</em> in the initializer.</li></ul><p>By default, our factory will pick configuration values from the global environment hash: <em>consumer_key</em>, <em>consumer_secret</em>, <em>access_token</em> and <em>access_token_secret. </em>These values were configured in <a href="https://blog.codeminer42.com/go-full-stack-rails-the-backend-a94b4d0e8897">part 1</a>.</p><p>And of course — we start off with a test. How might we test this? It’s fortunate that <em>Twitter::REST::Client</em> exposes attribute accessors which we can use to query configuration tokens and make sure our instance is correctly configured. Let’s write a spec with just that:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/03f58eb1342b31bfa514a31bbd41c135/href">https://medium.com/media/03f58eb1342b31bfa514a31bbd41c135/href</a></iframe><p>To make this spec pass the following code will suffice:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2af4fced28d400d271b9f35809b9eabb/href">https://medium.com/media/2af4fced28d400d271b9f35809b9eabb/href</a></iframe><p>Now we need another example to make sure missing configuration values are picked up from the ENV hash. Let’s have this example within a new context:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7aaf4a45f6e956b7962df90714f41863/href">https://medium.com/media/7aaf4a45f6e956b7962df90714f41863/href</a></iframe><p>Simple enough. Notice our conservatism when working with ENV variables. Since ENV is global, we must be careful to backup and restore the values between spec runs as to not mess with other examples which may rely on them.</p><p>To make this spec pass we need our code to be aware of the default values:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a394d778afcc3a27e33c7a2fbfd9ac67/href">https://medium.com/media/a394d778afcc3a27e33c7a2fbfd9ac67/href</a></iframe><p>And here’s what our test runner says, yay!</p><pre>TwitterClientFactory<br> when config is not passed<br>   picks config values from the environment<br>   #call<br>     builds a twitter client class with the passed config</pre><pre>Finished in 0.00576 seconds (files took 0.2973 seconds to load)<br>2 examples, 0 failures</pre><h4>Reviewing wrapper requirements</h4><p>Given what has been discussed on our last post, the wrapper class might return a result object containing tweets plus one of the following state symbols: <em>:ok</em>, <em>:not_found</em> or <em>:forbidden</em>. Tweets from these last two states must be an <strong>empty</strong> collection.</p><p>To implement this confidently we need to find out how twitter client behaves regarding the following timeline states: <em>ok</em>, <em>not_found</em> and <em>forbidden</em>.</p><h4>Further spiking out Twitter gem</h4><p>Let’s open our trustworthy rails console and see what happens when querying a non-existing timeline. Since we already have a <em>TwitterClientFactory, </em>that’ll be easy as pie:</p><pre>&gt; client = TwitterClientFactory.new.call<br>&gt; client.user_timeline(&#39;i-am-pretty-sure-i-dont-exist-ha!&#39;)<br>Twitter::Error::NotFound: Sorry, that page does not exist.<br>from /Users/thiago/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/twitter-5.16.0/lib/twitter/rest/response/raise_error.rb:15:in `on_complete’</pre><p>Oops… it throws a <em>Twitter::Error::NotFound</em> exception. And what about when a user forbids access to his timeline? Let’s see:</p><pre>&gt; client.user_timeline(&#39;mikey&#39;)<br>Twitter::Error::Unauthorized: Not authorized.<br>from /Users/thiago/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/twitter-5.16.0/lib/twitter/rest/response/raise_error.rb:15:in `on_complete’</pre><p>That’s a <em>Twitter::Error::Unauthorized </em>exception.</p><p>You may have noticed we are taking a different direction with our own design: although these situations are exceptional for the gem, they are <strong>not</strong> exceptional for our wrapper class; they are just part of the normal workflow. That said, we can visualize our wrapper as <strong>an adapter which happens to “fix” these mistakes and massage the data to a format our application can easily consume</strong>.</p><p>But that’s not all, there’s still something weird with the twitter gem. Let’s back up for a moment and build a <em>client</em> with invalid configuration:</p><pre>&gt; client = TwitterClientFactory.new.call(&#39;access_token&#39; =&gt; &#39;invalid&#39;)<br>=&gt; #&lt;Twitter::REST::Client:0x0055728659b548<br> <a href="http://twitter.com/access_token">@access_token</a>=&quot;foo&quot;,<br> <a href="http://twitter.com/access_token_secret">@access_token_secret</a>=&quot;your_twitter_access_token_secret&quot;,<br> <a href="http://twitter.com/consumer_key">@consumer_key</a>=&quot;you_twitter_key&quot;,<br> <a href="http://twitter.com/consumer_secret">@consumer_secret</a>=&quot;your_twitter_secret&quot;&gt;</pre><p>Now let’s see what happens when querying a valid timeline using <em>invalid configuration</em>:</p><pre>&gt; client.user_timeline &#39;thiagoaraujos&#39;<br>Twitter::Error::Unauthorized: Invalid or expired token.<br>from /home/thiago/.rbenv/versions/2.3.1/lib/ruby/gems/2.3.0/gems/twitter-5.16.0/lib/twitter/rest/response/raise_error.rb:15:in `on_complete’</pre><p>What!!?? That’s the same <em>Twitter::Error::Unauthorized</em> error that we saw before!</p><p>It turns out the gem uses the same kind of exception for when a timeline is forbidden and also when a token is invalid or expired. That means we need to use the exception message in our implementation to figure out which situation it is.</p><p>Now that we know how our client collaborator actually behaves, it’s time to finally implement our wrapper!</p><h4>Implementing the wrapper: mocking collaborators</h4><p>What immediately comes to your mind when thinking about the timeline wrapper? For me is that it <em>collaborates</em> with a Twitter client object. Let’s analyze how this collaboration might work:</p><pre># We initialize our instance with a collaborator<br>twitter_timeline_hub = TwitterTimelineHub.new(twitter_client)</pre><pre># A user_timeline message is sent internally to twitter_client<br># Our class wraps and delivers the result<br>result = twitter_timeline_hub.call</pre><pre># The result is a struct with the following attributes:<br>puts result.status # :ok<br>puts result.tweets # filtered tweets</pre><p>That translates to the following spec example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c83eb1fb9dbb969f0460333765eeed4d/href">https://medium.com/media/c83eb1fb9dbb969f0460333765eeed4d/href</a></iframe><p>I encourage you to keep running this spec while implementing exactly what the error message points at each step. Due to our constraints, we will go straight to the code necessary to make it pass:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f94a290fc1474d753782064cbc16592/href">https://medium.com/media/3f94a290fc1474d753782064cbc16592/href</a></iframe><p>And here’s what we get after running our spec again:</p><pre>TwitterTimelineHub<br>  #call<br>    collaborates with twitter_client to get a timeline and delivers a result struct</pre><pre>Finished in 0.01193 seconds (files took 0.29645 seconds to load)<br>1 example, 0 failures</pre><p>Awesome! It’s time to work on our first context: <em>when the timeline is found</em>.</p><h4>When the timeline is found</h4><p>Some <em>Twitter::Tweet</em> objects are likely to be delivered by the underlying client, so we need to traverse <em>Twitter::Tweet </em>relationships and extract exactly what we need from them, as has been determined in our first spike of our <a href="https://blog.codeminer42.com/go-full-stack-rails-the-backend-a94b4d0e8897#.8fgt6cd3k">first post</a>.</p><p>We need a helper method to stub out the “real” <em>Twitter::Tweet</em> objects:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4cac760b146ba2fea416b143eb88c095/href">https://medium.com/media/4cac760b146ba2fea416b143eb88c095/href</a></iframe><p>It will be used only once, but the point is that it makes our spec more readable because it abstracts <em>instance</em> <em>double</em> details which would otherwise make the example rather noisy.</p><blockquote>I would like to note that <a href="https://www.destroyallsoftware.com/blog/2014/test-isolation-is-about-avoiding-mocks">deep reaching within stubs</a> is generally not a good practice, but here we can assume the gem has a stable enough API that we can trust. We depend on it because there’s no other way around; that’s how the gem has been designed and it’s our role to massage the data to whatever format is needed.</blockquote><p>Our next spec is quite similar to the first one, but we don’t need to mock the collaborator anymore — which means <em>not expecting the collaboration to happen</em>, because that’s already been expected; moreover, we will have it deliver actual tweets instead of an empty collection:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c1c66fa91c4e034e589b1d435643f1f5/href">https://medium.com/media/c1c66fa91c4e034e589b1d435643f1f5/href</a></iframe><p>Moving this spec to green is quite straightforward:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7a510aab3565668297ecd8aa52a6e89d/href">https://medium.com/media/7a510aab3565668297ecd8aa52a6e89d/href</a></iframe><p>But the code is a bit crowded… let’s do the TDD refactor step and introduce some private methods to aid in readability:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a66e0f017e92063a5619442ea443882/href">https://medium.com/media/0a66e0f017e92063a5619442ea443882/href</a></iframe><p>Awesome, now it looks good and expresses our intent more concisely: we are “filtering” the original <em>Twitter::Tweet</em> objects and transforming them into plain hashes.</p><h3>When the timeline is not found or forbidden</h3><p>We’ve got other regular cases to deal with: <em>not_found</em> and <em>forbidden</em>. Remember: they’re not exceptional!</p><p>We need to force our fake <em>double</em> to throw a “not found” exception in order to mirror the gem behavior correctly. Here’s the spec for this case:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eec1934b9b55ab49ce064c98559be253/href">https://medium.com/media/eec1934b9b55ab49ce064c98559be253/href</a></iframe><p>And a very simple change to the <em>call</em> method makes our spec pass:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f786f69af3435068291f03f23336e47f/href">https://medium.com/media/f786f69af3435068291f03f23336e47f/href</a></iframe><p>The “forbidden” case is very similar, except that the Twitter client behavior is to throw a <em>different</em> exception (unauthorized):</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f1bfe310f42fdd383fa2f0156808dc0a/href">https://medium.com/media/f1bfe310f42fdd383fa2f0156808dc0a/href</a></iframe><p>And similarly, we can make it pass with a super straightforward update to the <em>call</em> method:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f2ccdca743b9b04ee94c4d292031830/href">https://medium.com/media/3f2ccdca743b9b04ee94c4d292031830/href</a></iframe><p>Notice how the format of our return value is consistent and predictable, which also makes our class easier to reason about — since there are no special <em>nils </em>to deal with.</p><p>But… hold off, we’re not done yet, there’s still an edge case to tackle!</p><h4>Treating the edge case of invalid or expired token</h4><p>Do you remember that an <em>unauthorized</em> error is thrown by the gem for the “<em>invalid or expired token”</em> situation? Well, if that ever happens we simply want to re-throw the exception instead of assuming that timeline access is forbidden. That case might be rare though, and might only happen with new developers setting up the application. Nevertheless, we want to avoid them a possible debugging headache.</p><p>Let’s write a spec for that. It is similar to the previous one, but it also takes the error message into account and asserts that the exception will be propagated over the call stack — and not swallowed up!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78384d804ca833536f64a0f6911a7d7e/href">https://medium.com/media/78384d804ca833536f64a0f6911a7d7e/href</a></iframe><p>And here’s the complete file with our <strong>final</strong> implementation:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5d42818d1bad8d79354a70fd0288b78/href">https://medium.com/media/d5d42818d1bad8d79354a70fd0288b78/href</a></iframe><p>And it’s finally over 🎉! You can try out the endpoint in Rails console, as to eliminate any skepticism you might have:</p><pre>&gt; app.get app.twitter_timeline_path(‘thiagoaraujos’)<br>Started GET “/twitter_timeline/thiagoaraujos” for 127.0.0.1 at 2016–10–06 11:15:03 -0300<br>Processing by TwitterTimelineController#show as HTML<br> Parameters: {“id”=&gt;”thiagoaraujos”}<br>Completed 200 OK in 1209ms (Views: 1.5ms | ActiveRecord: 0.0ms)</pre><pre>=&gt; 200<br>&gt; app.response.parsed_body<br>=&gt; {&quot;tweets&quot;=&gt;<br>  [{&quot;created_at&quot;=&gt;&quot;2016-10-01T14:36:09.000+00:00&quot;,<br>    &quot;screen_name&quot;=&gt;&quot;thiagoaraujos&quot;,<br>    &quot;text&quot;=&gt;&quot;RT <a href="http://twitter.com/_ericelliott">@_ericelliott</a>: \&quot;We only hire the best\&quot; hurts recruiting efforts. Hire smart people who love to learn. You&#39;ll hire faster and build more…&quot;,<br>    &quot;mentions&quot;=&gt;[&quot;_ericelliott&quot;]},<br>  ...]<br>&gt; app.get app.twitter_timeline_path(&#39;you-wont-find-me-ever&#39;)<br>Started GET &quot;/twitter_timeline/you-wont-find-me-ever&quot; for 127.0.0.1 at 2016-10-06 11:16:46 -0300<br>Processing by TwitterTimelineController#show as HTML<br>  Parameters: {&quot;id&quot;=&gt;&quot;you-wont-find-me-ever&quot;}<br>Completed 200 OK in 868ms (Views: 0.4ms | ActiveRecord: 0.0ms)</pre><pre>=&gt; 200<br>&gt; app.response.parsed_body<br>=&gt; {&quot;tweets&quot;=&gt;[], &quot;status&quot;=&gt;&quot;not_found&quot;}</pre><h3>But where are our integrations tests?</h3><p>Stubs are a great tool for isolated unit testing, designing collaborators and emulating external libraries. It’s worth noting that they provide <em>failure localization</em> — which means a unit test is only bound to fail due to reasons pertaining to the object under test, and never because of defects in its collaborators. Working with stubs is a great design exercise: you can clearly see coupling right in front of your eyes and minimize it to acceptable levels using the feedback you get.</p><p>Were we unit testing our classes with real collaborators, the chances of getting mucky errors would increase considerably and more tests would fail due to the same reasons — since code not related to the unit spec at hand would be part of the bunch. <em>Failure localization</em> mitigates this kind of problem.</p><p>That said, everything has trade offs, and the one with this style of testing is that a thin layer of integration specs is needed in order to prove objects and collaborators communicate as they should — otherwise unit specs may have their value diminished. With one or a few integration specs (without stubs) the <a href="http://martinfowler.com/bliki/TestPyramid.html">testing pyramid</a> becomes complete and most of the behavioral details are gracefully handled by the unit specs.</p><p>But… where’s our integration test? It turns out we already have one! It’s the end-to-end feature spec presented in our <a href="https://blog.codeminer42.com/go-full-stack-rails-the-backend-a94b4d0e8897#.8fgt6cd3k">first post</a>! It still needs some adjustments, though.</p><h3>Wrapping up</h3><p>Overall, I hope you have enjoyed the top-down design tips presented here. You can check all the backend code <a href="https://github.com/thiagoa/twitter_widget">in this GitHub repository</a>.</p><p>But hold off, the best is still to come! We have some cool JavaScript to work out on our next post, and it will be a lot of fun! Thanks for reading, and if you have any questions or noteworthy approaches please leave them in the comments!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=339db75a5db0" width="1" height="1" alt=""><hr><p><a href="https://medium.com/codeminer-42/go-full-stack-rails-the-backend-part-2-339db75a5db0">Go Full Stack Rails: The Backend part 2</a> was originally published in <a href="https://medium.com/codeminer-42">The Miners</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>