<?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 Pete Hanner on Medium]]></title>
        <description><![CDATA[Stories by Pete Hanner on Medium]]></description>
        <link>https://medium.com/@petehanner?source=rss-146710cad261------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*TNuefAFuVXfrbODPh8eaYw.jpeg</url>
            <title>Stories by Pete Hanner on Medium</title>
            <link>https://medium.com/@petehanner?source=rss-146710cad261------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 17:34:37 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@petehanner/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[App Journal: Building the trivia gameplay page]]></title>
            <link>https://petehanner.medium.com/app-journal-building-the-trivia-gameplay-page-ec0c625d3ebd?source=rss-146710cad261------2</link>
            <guid isPermaLink="false">https://medium.com/p/ec0c625d3ebd</guid>
            <dc:creator><![CDATA[Pete Hanner]]></dc:creator>
            <pubDate>Sat, 24 Oct 2020 19:15:24 GMT</pubDate>
            <atom:updated>2020-10-24T19:15:24.739Z</atom:updated>
            <content:encoded><![CDATA[<p>It’s been a while since <a href="https://medium.com/@petehanner/how-to-set-up-react-global-state-with-hooks-not-redux-263888b9e36c">my last blog post on building a basic trivia app using React with Redux-less global state</a> — quarantine has been weird and time for personal projects ebbs and flows, but I’m back at it. When I last left off, I had set up global state using just React hooks and the Context API, and tested basic functionality by making an external API call and saving the result to my store. My next step is to set up some basic app usage with this store data available. My goals for this phase of development are to split the app into separate welcome and gameplay pages, and go from the welcome screen to the first trivia question when a user hits the “Play” button.</p><p>As I mentioned in the first blog, please keep in mind this is a basically-live chronicle of me learning and experimenting as I go. I’m publishing these pretty much as I wrap up each development phase; there’s some editing to keep things straightforward, and I’ll try to edit out any blatant errors down the road should they come to my attention, but I may make smaller mistakes or eschew best practices without knowing. These blogs are meant as a reference material for folks working on similar projects, not a tutorial.</p><p>Okay disclaimer over — let’s code!</p><h3>Step 1: Split the app into welcome and gameplay pages</h3><p>Now that I’m starting to build the app out, it’s time to break the code into components and out of App.js, which will control the render of top-level components. To start, I move the existing code I have from App.js into a WelcomePage component and create a new GamePage component. Eventually this will hold the multiple choice question interface, but right now I&#39;m just checking that routing between views works correctly, so I&#39;m just having it be simple text for now.</p><p>As before, I’m only explicitly including imports that are new/immediately relevant for the sake of space; the rest should be implied. I’m also trying to pick my packages judiciously; I’m using <a href="https://reactrouter.com/web/guides/quick-start">React Router</a> to render top-level components, and <a href="https://chakra-ui.com/">Chakra UI</a> to handle my display components so I can focus on the meat of the app’s functionality.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2e9ef86ccf2c5594d1e04cfecfb99d52/href">https://medium.com/media/2e9ef86ccf2c5594d1e04cfecfb99d52/href</a></iframe><h3>Step 2: Wireframe the gameplay page</h3><p>Now I need to set up my gameplay page in its basic form. I’ll worry about answering and advancing questions down the line, right now I just want to make sure that the user interface displays all the necessary information and is configured correctly that I can build functionality on top of it.</p><p>I have an array of 30 questions, and need to show just one of them at a time. This means I need to add another value to my state, keeping track of which question the user is currently on. Chances are I could probably get away with just using the useState hook inside the GamePage component, but A) one of my main goals with this project is building familiarity with pure-React global state so I&#39;m okay with a little added complexity if it means getting that practice, and B) this way might actually end up being simpler if I end up having to do more prop drilling than anticipated.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7ad0063d52512d7b483803d3112c26b3/href">https://medium.com/media/7ad0063d52512d7b483803d3112c26b3/href</a></iframe><p>Since GamePage is a top-level component, I&#39;m keeping the core logic there and creating a display component TriviaCard to render the UI. I&#39;ve already reorganized WelcomePage in a similar way, having it render just plain text and an ImportTriviaButton component, not shown here.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/eb1001bcb9f8a223fcb898353ff3a3e9/href">https://medium.com/media/eb1001bcb9f8a223fcb898353ff3a3e9/href</a></iframe><h3>Step 3: Handle prop/routing errors</h3><p>This works for when I start from the home page, but I find that if I refresh the page or try to go straight to the /play route, I get an error caused by questionObj not yet being defined. After a little experimenting, I came up with the following additions to GamePage. This checks for questionObj and redirects to the root path if it isn&#39;t set. It also uses a blank string for the destructuring assignment of category and question, just as an additional safety measure to avoid a possible null error. Disclaimer that this approach worked for me, but there may be a more conventional way to achieve the same effect.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d5c7df17683f8fbfbda5bb0c7a15fcbe/href">https://medium.com/media/d5c7df17683f8fbfbda5bb0c7a15fcbe/href</a></iframe><h3>Step 4: Clean up the interface</h3><p>I’ve also noticed that the game page itself includes HTML entities (like &amp;quot; for quote marks). I could use dangerouslySetInnerHTML, but this is a free, open-source API. Even if it&#39;s probably safe, it&#39;s still not worth the risk. There are multiple libraries that decode HTML entities, but like I mentioned I&#39;m trying to limit my packages installed, so I&#39;m writing my own solution. I create a dictionary-style object called htmlEntities that matches the key of the entity code with the value of the actual character to print. I then write a function htmlDecode() that takes a string and uses the replace() method to sub in the correct characters. (This throws an error if quetionObj isn&#39;t loaded, hence the second line). The category, question, and answer options are then passed through the function before being sent as props to the trivia card. Note this requires let instead of const in the destructuring assignment since the values are being overwritten.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0c53b9eeda0bbef63064cd5b45ae2ad3/href">https://medium.com/media/0c53b9eeda0bbef63064cd5b45ae2ad3/href</a></iframe><h3>Step 4.5: Realize you over-engineered a solution</h3><p>Well folks, turns out that the Open Trivia API has multiple encoding options, including URL encoding that can be processed just with the out-of-the-box decodeURIComponent() JS function 🤦‍♂️</p><p>I&#39;m refactoring the app to use this <em>much</em> simpler solution, but still leaving all my prior work in this blog. A) It shows the real steps taken and keeps them around as reference for anyone working on a similar problem without a similar solution, B) it emphasizes the importance of <strong>reading your documentation</strong>, and C) it serves as a record of proof that, yes, these blogs are a live journal of my process, warts and all.</p><p>With that done, I’ve got basic trivia loading completed. For my next blog, I need to add functionality to progress through the questions sequentially and track correct vs. incorrect answers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ec0c625d3ebd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to set up React global state with hooks, not Redux]]></title>
            <link>https://petehanner.medium.com/how-to-set-up-react-global-state-with-hooks-not-redux-263888b9e36c?source=rss-146710cad261------2</link>
            <guid isPermaLink="false">https://medium.com/p/263888b9e36c</guid>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Pete Hanner]]></dc:creator>
            <pubDate>Sun, 27 Sep 2020 17:21:45 GMT</pubDate>
            <atom:updated>2020-09-27T17:21:45.068Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*JIbTG_3C_2XWq2LU" /><figcaption>Photo by <a href="https://unsplash.com/@polarmermaid?utm_source=medium&amp;utm_medium=referral">Anne Nygård</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>When I learned React, the bootcamp curriculum featured a blend of class and functional components, hooks were covered in just a single afternoon lecture, and we used Redux for global state management. Ever since starting my post-bootcamp career, I’ve been working pretty minimally in JavaScript, and all in either vanilla JS or jQuery. The React world has also had a lot of exciting changes and certain norms have been codified in the meantime. Everything is functional components now and hooks are the way of the future, but my interest was really piqued by hearing that global state is now possible to implement purely in React — no Redux needed. I love React and want to keep up my skills, so I’ve started building a pretty basic front-end app to get a solid grounding in some more contemporary practices that I didn’t get a chance to dive into in bootcamp. In the interest of helping those coming behind me, I’ve decided to blog about my process and any insights I have along the way.</p><p>PLEASE keep in mind that this is a living document being written as I figure this project out. I might not necessarily be following best practices, and could potentially make some mistakes. I (personally) find following along with a practical project a more useful learning tool than lessons or tutorials, which can often get abstract or put the cart before the horse, but it does come with tradeoffs. I’ll try and note where I’m just taking my best guess, and even come back to edit any egregious mistakes if they arise, but be aware this isn’t an expert tutorial (and if you happen to catch any major oopsy-goofs on my part, please contact me!)</p><p>Okay with that out of the way, let’s get started!</p><p>I love trivia, so I’m making a trivia app using the <a href="https://opentdb.com/api_config.php">Open Trivia Database API</a>. My goal is to make a 30-question game of 10 easy, medium, and hard questions apiece where users race against the clock to get as many questions correct in as little time as possible. I might add some bells and whistles down the line, but for now I’m just focusing on that core functionality.</p><p>My initial goal is to explore how to implement global state using hooks instead of Redux. Two articles that were of immense help getting up and running were <a href="https://blog.logrocket.com/use-hooks-and-context-not-react-and-redux/">this one by Ebenezer Don of LogRocket</a> and <a href="https://medium.com/@martin.crabtree/react-creating-a-redux-like-global-state-with-the-usecontext-and-usereducer-hooks-89aa2b27dbc5">this Medium article by Martin Crabtree</a>. Both implement state slightly differently and I ended up leaning more towards the second for my own project, but both are hugely useful.</p><p>Here’s the top level overview of what I need to do for phase one:</p><ol><li>Create a basic reducer with its initial state</li><li>Create a store that contains global state and make it globally accessible</li><li>Make an API call that interacts with global state to ensure everything works at a basic level before building on top of it</li></ol><p>Now that we have an outline of our basic steps, let’s get into the actual implementation.</p><h3>Step 1: Basic reducer + initial state</h3><p>After running create-react-app, I create a new file called store.js in the src folder. This will be in charge of the global state. For values I&#39;ll need to keep in state, I know that I need one to keep track of whether the API is fetching, and an array to keep track of the questions. More values will definitely be necessary down the line, but remember this is just a basic start. As with Redux, the reducer is a pure function. To test my initial setup, I&#39;m aiming to make an API call that retrieves 30 questions and saves them in state, so for now I&#39;m just going to make an action for when the call is dispatched, and an action apiece for when the call returns successfully and unsuccessfully. I&#39;m including console logs for in-browser testing purposes of seeing exactly what I&#39;m getting back.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7446d4bb73d3501886d14c1b39130a19/href">https://medium.com/media/7446d4bb73d3501886d14c1b39130a19/href</a></iframe><h3>Step 2: Make state globally accessible</h3><p>Next I use React’s <a href="https://reactjs.org/docs/context.html">Context API</a> to create a context object with its initial state set to, appropriately enough, initialState. Then I create a store provider component by creating a function that uses <a href="https://reactjs.org/docs/hooks-reference.html#usereducer">the </a><a href="https://reactjs.org/docs/hooks-reference.html#usereducer">useReducer hook</a> and returns the context object&#39;s Provider component with the reducer hook set as its value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8329ae7586d3b8629883d35f0f1c0615/href">https://medium.com/media/8329ae7586d3b8629883d35f0f1c0615/href</a></iframe><p>In order to make state globally accessible, I just need to wrap my app component in the StoreProvider...</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/87544e82a7b8bbfddcc9d3be195371c2/href">https://medium.com/media/87544e82a7b8bbfddcc9d3be195371c2/href</a></iframe><p>… and include the following useContext call within any component that needs to access global state:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43f5e7038da6726cbfdcf79583271777/href">https://medium.com/media/43f5e7038da6726cbfdcf79583271777/href</a></iframe><h3>Step 3: Test global state with API call</h3><p>Eventually I’ll need to split the app up into a component hierarchy, but for purposes of testing that everything is wired up correctly I’m just keeping everything in App.js for now. I&#39;m also trying to keep my imported packages to a minimum, but I do like <a href="https://github.com/axios/axios">axios</a> for making HTTP requests.</p><p>I create a component clickMe that when clicked, fires the function fetchAndDispatchTrivia. This function dispatches &quot;FETCH_TRIVIA_START&quot; to tell global state that the app is in the process of fetching. It then initializes an empty array to store the trivia questions, and chains together three separate calls to the API (for 10 easy, medium, and hard questions), pushing the results of each call to the questions array. If all goes well, the function should dispatch a success action and a 30-member array of trivia questions should be saved to global state. Otherwise it should throw an error. While the app is fetching, the &quot;Click for trivia&quot; text should be replaced with a &quot;please wait&quot; component (based on reading the isFetching value from global state).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c2538a88c8c0c36fbd174ed70ddd19bd/href">https://medium.com/media/c2538a88c8c0c36fbd174ed70ddd19bd/href</a></iframe><p>Testing in-browser, everything works as expected, so I’m free to move on to more core implementation of the app interface, which I’ll cover in my next blog installment.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=263888b9e36c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Finally Figured Out Recursion]]></title>
            <link>https://petehanner.medium.com/how-i-finally-figured-out-recursion-8e4a185ec7a?source=rss-146710cad261------2</link>
            <guid isPermaLink="false">https://medium.com/p/8e4a185ec7a</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[recursion]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Pete Hanner]]></dc:creator>
            <pubDate>Sun, 12 Jan 2020 15:37:41 GMT</pubDate>
            <atom:updated>2020-01-12T15:47:06.515Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/650/0*gXXq_xj9P9YTSqAI.jpg" /></figure><blockquote>Let’s start at the end, a very good place to start.</blockquote><p>As I suspect a lot of people feel at some point, writing recursive functions seemed dense and counterintuitive to me for a while. You call a function, inside that function itself? How does that even work? Why would you do it? What’s the actual design pattern of making it properly?</p><p>While working through a coding challenge, I finally had a breakthrough that helped me answer all those questions, as well as identify the source of my previous hang-ups. I realized that I’d been approaching recursion problems backwards, because I’d been approaching them forwards. When you’re starting to write a recursive problem, it’s a good idea to start it from the end and work backwards from there. Because that’s the path forwards. Confusing? Yeah, recursion is. But I’ll explain. I’m by no means an expert, but hopefully this will help other greenhorns have a similar breakthrough and start down the path towards mastering recursion.</p><p>Here are the general realizations I had about recursion, and then we’ll look at an example:</p><ul><li>Recursion patterns can be used to do some kind of repeated work for an indefinite number of times until certain criteria are met.</li><li>At the end of a recursion pattern, there should be some kind of check to see if the work needs to be done again. If not, exit the function and return the desired result. But if so, start the pattern over.</li><li>This means that when writing a recursive function, you can start at the end with a simple if-else statement. In your if statement, check if your desired work is done and return the result if so. If not, just invoke the function again.</li></ul><p>Let’s look at an example problem. Let’s say we’re trying a function to return a count of colleges and universities that A) have a given substring in their name and B) are over a given student population size. We’ll say that to accomplish this, we’re querying an API where a name= argument in the URL will return only results containing the matching substring. Our challenge, however, is that the API results are paginated and we need to go through all the result pages to get our final answer.</p><p>The full function is below (or at least the essential elements), and then we’ll break it down.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fjsfiddle.net%2Fpetehanner%2Foaw3xtpv%2Fembedded%2F&amp;url=https%3A%2F%2Fjsfiddle.net%2Fpetehanner%2Foaw3xtpv%2F&amp;image=https%3A%2F%2Fwww.gravatar.com%2Favatar%2Fc3ae1dee993bf5aac82a04cd488526e0%3Fs%3D80&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=jsfiddle" width="600" height="400" frameborder="0" scrolling="no"><a href="https://medium.com/media/3f4eb6f5c7c4b6123cc6483263fc62a7/href">https://medium.com/media/3f4eb6f5c7c4b6123cc6483263fc62a7/href</a></iframe><p>Our API query always returns an object with a total_pages key, so we can use that to control our recursive function:</p><pre>const json = JSON.parse(body)<br>const lastPage = json[&#39;total_pages&#39;]</pre><p>Using that lastPage variable, we can set up the recursive logic at the end of the makeRequest() function:</p><pre>if (page === lastPage) {<br>  return count<br>} else {<br>  page++<br>  makeRequest()<br>}</pre><p>If there are no more pages to query, then we can return our count variable. Otherwise, we increment the page number (which is interpolated into the URL for our next query) and makeRequest() calls itself, <em>within</em> itself.</p><p>The main body of makeRequest() involves sending a query, looping over results, and incrementing the count variable, but honestly — none of that matters here. This is just a basic example. We’re talking about recursion as a general concept. The body of the function can do whatever you want it to; the important part is the logic at the end. By its very definition, something recursive will keep repeating forever until it breaks. It’s technically recursion if we accidentally write a while loop and forget to increment the counter. In this case, the recursion breaks (eventually) through computer error. When we write recursive functions, however, we harness the chaos of recursion by intentionally writing in conditions to break the cycle. As long as you know when you want your cycle to break, you can write a recursive function. All it takes is a simple if-else statement to check at the end of each cycle.</p><p>Begin from the end.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8e4a185ec7a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting Rails to Work with Catalina/zsh]]></title>
            <link>https://petehanner.medium.com/getting-rails-to-work-with-catalina-zsh-84146e1d2099?source=rss-146710cad261------2</link>
            <guid isPermaLink="false">https://medium.com/p/84146e1d2099</guid>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[zsh]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[mac]]></category>
            <dc:creator><![CDATA[Pete Hanner]]></dc:creator>
            <pubDate>Tue, 26 Nov 2019 20:31:58 GMT</pubDate>
            <atom:updated>2019-11-27T16:55:29.072Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wMVx7QeJ7T06a4d933WLYQ.png" /></figure><p>With the release of MacOS Catalina, <a href="https://insights.dice.com/2019/06/12/macos-catalina-zsh-bash-xcode-11/">Apple has abandoned the bash shell in favor of zsh</a>. After adjusting, I actually prefer zsh. It’s user friendly, even more so with the virtually-essential oh-my-zsh plugin, and I really like the file navigation and autocomplete features.</p><p>Much to my dismay, however, I found that my older Rails projects were <em>not</em> playing nicely with zsh. Trying to bundle i or rails s especially seemed to be leading me around through an Ouroboros of error messages. Missing gems, wrong permissions to install said gems, and the Terminal insisting “Your Ruby version is X.X.X, but your Gemfile specified X.X.Y” seemed to be the main cyclical themes.</p><p>After a great deal of Googling and frustration, I finally was able to get the new setup working. I must have looked through four or five dozen StackOverflow and forum conversations, but credit goes to <a href="https://github.com/ohmyzsh/ohmyzsh/issues/6190">this GitHub thread</a> for ultimately guiding me to the solution. Hopefully this post will help save someone the hair-pulling and dot-connecting I had to go through.</p><blockquote><strong>DISCLAIMER 1:</strong> I manage Ruby through rbenv rather than rvm, but have switched back and forth at least twice. (Which is Dumb, I know). I also had a bad habit several years back, when I was relatively computer-savvy but hadn’t touched actual programming, of messing around quasi-blindly in the Terminal and throwing around sudo commands perhaps a bit too cavalierly. (Which is even Dumber, I know). Point being, it’s entirely possible that I laid the groundwork for my own headaches years ago, and the solution below might be relatively particular to my own uniquely tormented machine. Your results may vary.</blockquote><blockquote><strong>DISCLAIMER 2:</strong> I only cracked this in the last hour or so of writing this blog post and have therefore only done basic, golden-path testing. Rails commands seem to be humming along smoothly for old projects I’m just refactoring, but it’s entirely possible that unforeseen errors may arise with more complex usage. <em>Please</em> shoot me a message if this is the case and I’ll update the post.</blockquote><p>And now for the solution…which is shorter than the disclaimers. Run the four lines below in your Terminal:</p><pre>echo &#39;export PATH=&quot;$HOME/.rbenv/bin:$HOME/.rbenv/shims:$PATH&quot;&#39; &gt;&gt; ~/.zshenv<br>echo &#39;eval &quot;$(rbenv init -)&quot;&#39; &gt;&gt; ~/.zshenv<br>echo &#39;source $HOME/.zshenv&#39; &gt;&gt; ~/.zshrc<br>exec $SHELL</pre><p>The first two commands add two lines to your .zshenv file that properly connect rbenv to zsh. The third one adds a line to your .zshrc file that connects it to .zshenv. The final command does a complete reload of the shell as if you had logged in fresh.</p><p>As best I can tell, the first two lines are the most important — they actually make zsh and rbenv play nice with each other. If your .zshrc file already contains the line source $HOME/.zshenv, the third line shouldn’t be necessary. I also believe you can just restart your computer rather than run the fourth command. That said, I’ve included all the steps I took exactly, just in case I’ve made an incorrect assumption anywhere.</p><p>As mentioned above, please let me know if anything above is inaccurate or secretly broken, and I’ll update with a disclaimer. Hopefully this helps folks out there!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84146e1d2099" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Make Your Life Easier With Atom Packages]]></title>
            <link>https://petehanner.medium.com/make-your-life-easier-with-atom-packages-1ef0ae8ed190?source=rss-146710cad261------2</link>
            <guid isPermaLink="false">https://medium.com/p/1ef0ae8ed190</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[atom]]></category>
            <dc:creator><![CDATA[Pete Hanner]]></dc:creator>
            <pubDate>Wed, 06 Nov 2019 15:40:23 GMT</pubDate>
            <atom:updated>2019-11-06T15:40:23.137Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*_50zUrphPQtaTZe1" /></figure><p>Programmers are lazy. But, like, the good kind of lazy. When you’re trying to piece together a particularly tricky project, why make life difficult for yourself with nuts and bolts? Most major editors come with a wide array of plugins explicitly intended to move mental effort away from coding basics so you can focus on making your actual product the best it can be.</p><p>My favorite editor hands-down is <a href="https://atom.io/">Atom</a>, made by the team from GitHub. Although Flatiron recommends VSCode officially, I’ve really enjoyed Atom due to the customizability that‘s so core to its design philosophy. There are a million ways to set up this editor, and yours will no doubt be unique from mine, but here are a few of the packages I’ve found essential in my coding journey:</p><h4>Themes: <a href="https://atom.io/themes/one-dark-ui">One Dark</a> and <a href="https://atom.io/themes/darker-one-dark-syntax">Darker One Dark</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_8uYzw5bCJQqaEV0TO3VqA.png" /></figure><p>These are my UI and syntax themes, respectively. If you’re going to be staring at a computer screen all day, why not make it easy on the eyes? These themes are minimalist and dark; the only pops of color are in the code you’re writing, which are vivid and have excellent, language-specific differentiations in color.</p><h4>Readability: <a href="https://atom.io/packages/atom-beautify">Atom Beautify</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7dCrCtUCk6M62-UOb_nljA.png" /><figcaption>This menu goes down further. Like, a <strong>lot</strong> further. And that goes for every supported language, which is a lot more. Like, a <strong>lot </strong>more.</figcaption></figure><p>There’s a classic coder saying about writing your code as if it will be maintained by a homicidal maniac who knows where you live. Sleep easy with Atom Beautify, an auto-formatter that indents, spaces, line-breaks, and generally cleans up your code according to style guides with a single keyboard shortcut. Settings are customizable per individual language, letting you choose between various formatting plugins as well as options within the Atom editor itself. It even differentiates between language flavors, so you can edit JavaScript, JSON, and JSX with different formats, for example.</p><h4>More Readability: <a href="https://atom.io/packages/indent-guide-improved">indent-guide-improved</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*quRLCjpywwKjn7cYaTtFkA.png" /></figure><p>Atom’s built-in indent guide draws handy lines from the beginning of block levels to their end, making it easier to follow the scope of your code. As useful as that is, this plugin makes it even better, highlighting the lines for your current scope and dimming others. Still not enough for you? Custom stylesheet rules are relatively manageable to implement, allowing you to set your own line weights, colors, and more for every focus level. Combine this with beautify and never be lost by another forgotten parenthesis or bracket ever again.</p><h4>Begone, Window Switching: <a href="https://atom.io/packages/platformio-ide-terminal">platformio-ide-terminal</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Kamba3fLrWUwxnuNY9iKBg.png" /></figure><p>If you’re debugging, the terminal is your worst enemy and your best friend. It’s also something you’ll be visiting roughly every 1.3 seconds, so why bother swiping between workspaces or Cmd-Tab-ing through every window you have open? This plugin lets you open up a terminal right in Atom. If you have a separate Terminal window open elsewhere, it even saves your command history across instances for your use.</p><h4>Seconds Add Up: <a href="https://atom.io/packages/autoclose-html">autoclose-html</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zKBUE93zkXoJah-Qt12DSg.png" /><figcaption>All these tags were closed automatically. You can’t tell in a static image, but just take my word for it. Or if you don’t believe me, just download the plugin and check for yourself.</figcaption></figure><p>If you’re doing web development, this is a must. Every time you type a &gt;, or a/ within angle brackets, this plugin closes the tag for you. This is one that seems small, but once you never have to remember to write a &lt;/div&gt; or any other closing tag again, you’ll never want to go back.</p><h4>git uh-oh --where-was-i: Atom <a href="https://atom.io/packages/svn">svn</a></h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*scoCiNph2kRIw1E9OhVLjg.png" /></figure><p>Given that it’s maintained by the GitHub team, Atom naturally has great git functionality. A number of plugins have enhanced this even further, but my favorite is svn. Files with changes since your last commit are highlighted in yellow in the tree view, with the exact lines marked by yellow bars in the gutter. The gutter also shows green bars for newly added lines and red arrows for deletions. New files are also highlighted green in tree view. Another plugin that sounds so simple, yet seems almost impossible to work without once you’ve gotten used to it.</p><h3>The World Is Your Oyster</h3><p>These are only a few of my favorite Atom packages — the list goes on in terms of language support, snippet collections, formatting helpers, color pickers, and tweaky little things that <em>may</em> have honestly distracted me more towards optimizing my environment set-up than actually coding.</p><p>Getting sucked into plugins is definitely a danger, and you definitely don’t want to go down that rabbit hole just for the sake of customizing. But used thoughtfully and purposefully, packages can make the nuts and bolts of coding <em>soooo</em> more easier and seamless. By taking mental energy away from boring, repetitive, and time-consuming tasks, you can better focus your efforts on creating efficient, beautiful, optimized code.</p><p>Try out some of these plugins to see if they help your coding journey, and next time you find yourself bogged down in mindless setup or boilerplate, take a look around the Atom packages collection and see if there’s already a tool out there to make your life easier.</p><p>After all, you’re programmer — be lazy! But like, the good lazy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1ef0ae8ed190" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Semantic UI React Grids for Fun and Profit*]]></title>
            <link>https://medium.com/swlh/semantic-ui-react-grids-for-fun-and-profit-e2a757c25649?source=rss-146710cad261------2</link>
            <guid isPermaLink="false">https://medium.com/p/e2a757c25649</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Pete Hanner]]></dc:creator>
            <pubDate>Thu, 24 Oct 2019 13:20:34 GMT</pubDate>
            <atom:updated>2019-10-25T21:04:56.790Z</atom:updated>
            <content:encoded><![CDATA[<p>*(neither fun nor profit guaranteed)</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yTiavMVBlXM4R5utw5S2JQ.png" /></figure><p>Let’s say, hypothetically, that we’re building a mini-RPG battle game. You know, like my partner German and I were for our Flatiron Mod 4 project. We want users to be able to select various items like weapons, armor, etc. and battle against other users with their selected loadout. When selecting their equipment, we want users’ options to be laid out in a nice little grid like the above. We’re working in React and have installed <a href="https://react.semantic-ui.com/">Semantic UI React</a> in our project. How do we get from a blank component to the beautiful image we have in our heads above?</p><h4>Step 1: Static Wireframing</h4><p>First things first. Ultimately, we want to gather data from our backend about the various equipment options of each type, and dynamically render them to the page. Before achieving that level of complexity, however, we should make sure we can get the page looking generally how we want it to. Our App.js contains a Route rendering the EquipmentPage component, which in turn contains the IconGrid component. This is where the bulk of our work will go.</p><p>To begin with, we’re only planning to have 9 options within each equipment type. A 3x3 grid is ideal here, but we want our app to be flexible. If we decide to add or remove options in the future, the app should be able to handle that by placing all items in a 3-column grid, even if the total number of items isn’t divisible by 3. We’ll stick with the basic 3x3 grid for our wireframe, but it’s useful to have a clear idea of potential scaling options and challenges at the outset. You can never plan for every eventuality, of course, but it never hurts to start with flexibility in mind.</p><p>By reading the Semantic docs, we can learn that Grid components wrap Grid.Row components, which in turn wrap Grid.Column components for each column in the grid. We want a basic square grid, so we want something like the code below. To see what our result might look like, let’s use placeholder images from <a href="https://www.fillmurray.com/">Fill Murray</a>, because obviously.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iMIfaPXYMNEo9ZF0NU2NCQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6K-8tu0S9LrtGnfJXIeu9g.png" /></figure><p>Perfect! We also want to have a card pop up that displays details for items when you click on them. This post focuses on building the grid so we won’t get into the detail card too much, but just know that this.props.equipClick() is a method from the parent that sends the object in a clicked grid square over to the right-hand container.</p><h4>Step 2: Identifying Patterns</h4><p>Looking at our basic wireframe, we can better understand the structure of what our end goal is. Getting the data from the backend is easy; the real challenge is figuring out how to process it. Let’s look at the code again and break it down:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iMIfaPXYMNEo9ZF0NU2NCQ.png" /></figure><p>We have a single Grid component at the highest level of our return. Within that component, we have three child components: each just a simple Grid.Row. No tags or any other bells and whistles. Each of those Grid.Rows in turn has three Grid.Column components. These columns each contain an Image with some tags. These Images are our only changing element — eventually they’ll contain the actual equipment items from our backend. As long as we can figure out how to dynamically place them in the code structure above, we’re golden!</p><h4>Step 3: Writing a Recipe</h4><p>Once we know the pattern, it can be tempting to jump right into coding. Our brains are smart, however, and are very good at building connections and understanding the general “concept” of a pattern without laying it out explicitly. Computers are very dumb, though. They’re fast and efficient and tireless, but ultimately only good at doing exactly what they’re told. For that reason, it’s a good idea to write out a <em>very explicit</em> ‘recipe’ or draw a detailed flowchart before ever writing a line of code. Break your task down into the smallest pieces imaginable, so small it almost seems dumb. Because your computer <em>is</em> dumb, and if your recipe’s logic breaks down at any point your computer will be very lost.</p><p>With that PSA out of the way, let’s see if we can write a recipe for the pattern above. Some background, first, though: At the level of App.js, we’re fetching data about all the equipment types and options to store in state. When the user selects a certain type of equipment (weapons, armor, etc.) from the main page, an array of objects for all equipment matching that type are passed down the component tree as a prop called type.</p><p>We know our return will be statically wrapped by a Grid component, so our recipe to build the grid might look something like this:</p><ol><li>Create a Grid.Row component.</li><li>Create a Grid.Column that holds the image for the first item in this.props.type and place it in the Grid.Row. (First column)</li><li>If another element exists in this.props.type, create a Grid.Column to wrap it and place it in the Grid.Row. Otherwise, return the finished Grid. (Second column)</li><li>If another element exists in this.props.type, create a Grid.Column to wrap it and place it in the Grid.Row. Otherwise, return the finished Grid. (Third column).</li><li>If another element exists in this.props.type, loop back to Step 1. Otherwise, return the finished Grid.</li></ol><h4>Step 4: Recipe → Code</h4><p>We want to loop over our this.props.type array of equipment options and make a Grid.Column holding an Image for every item. This type of operation implies a map().</p><p>The main challenge here is the pattern of threes. this.props.type is a flat array, but the Grid.Rows surrounding every three Columns interrupt the 1:1 transformation inherent to map(). Somehow we need to get our array into groups of three (or possibly fewer once the array runs out).</p><p>The solution: break this flat array out into a multidimensional array. If the broadest possible pattern is in groups of three Columns, we can split up our array into smaller chunks that can be looped over.</p><p>In order to do this, we start by initializing a copy of this.props.type that we can modify destructively, an empty array to serve as the outer layer for our whole table, and an empty array to hold an individual row:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DXH0KxFnlhn4Ww5npcd-eg.png" /></figure><p>We then move the three first members from our array of equipment options (typeCopy) into our gridRow array. To avoid errors, we always check that an element to add actually exists before moving it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IZC9x1l6fLwTsfqAmvA3Pw.png" /></figure><p>Once we’ve added three items (max) to the smaller array, we add it to the bigger array that will ultimately become our grid. The smaller array is then cleared out, and the while loop starts over as long as there are more items to shovel.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uk9_ob8WR6RdaHaKj6GLIQ.png" /></figure><p>We then loop over both arrays with a nested map(). Each of the members of gridArray is itself an array we can map over. We create a Grid.Row for each member of the outer array, within which we create a Grid.Column for each member of the inner arrays, all formatted how we want it to be laid out on the page:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CpNV6R8gWwxjS7oTSDoS-A.png" /></figure><p>In the end, our code looks like this altogether:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_tSiJuTfIY-8yO50NpbC1g.png" /></figure><p>So when we write our render() for the component, all we need is this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4G4Qap60X4juzza2QSQ45g.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eaVQzufeXfZwcbpdr8Difw.png" /></figure><p>Easy!</p><h3>Final Thoughts</h3><p>This is kind of a niche code problem. Whether or not this <em>specific</em> case will be useful to readers, I don’t know. Mainly, I wrote this as a way of thinking through coding problems generally. Too often, we can rush into the trap of throwing code at our problems until something works. Typing is so easy, after all, and we can always Cmd+Z and try something new until it sticks.</p><p>This is bad practice, though. At best, we run the risk of retaining garbage code that serves no purpose in the end and clutters our code. At worst, we land on a “solution” that solves our short-term problem but just duct tapes over problems that will rear up with a vengeance down the line in our projects.</p><p>Often, stepping away from the keyboard is the best possible decision. Write your problem down in plain English, explaining it <em>exactly</em> and thoroughly. You’ll often be surprised by the revelations that come from engaging with assumptions you didn’t even realize you were making. Once you’ve done that, do the exact same thing with your solution. Then, and only then, sit back down and start translating your thoughts into code.</p><p>You might not get the exact solution right away — German and I didn’t land on nested map()-ing until several tries in. But as long as you have a clear road map in front of you, all your coding will be working towards achieving your well-defined solution rather than blindly taking guesses that may compound your difficulty as you muddy the code.</p><p>Just remember, you can’t get to a destination unless you know what it actually is. Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e2a757c25649" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/semantic-ui-react-grids-for-fun-and-profit-e2a757c25649">Semantic UI React Grids for Fun and Profit*</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript promises and fetch()]]></title>
            <link>https://petehanner.medium.com/javascript-promises-and-fetch-33a5f5d13fe0?source=rss-146710cad261------2</link>
            <guid isPermaLink="false">https://medium.com/p/33a5f5d13fe0</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[technology]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Pete Hanner]]></dc:creator>
            <pubDate>Fri, 04 Oct 2019 14:17:56 GMT</pubDate>
            <atom:updated>2019-10-04T14:17:56.813Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*d_tvJXEfK1CDbuYz9KFuyw.jpeg" /></figure><p>As developers, we often need to gather data from external sources for use in our own programs. Doing this in JavaScript used to require clunky code or the use of outside libraries, but fortunately the Fetch API has in recent years made retrieving, adding, editing, and removing data from external databases easier than ever before. This API works by providing and resolving a series of promises. Let’s break down this process with a few examples.</p><h3>A basic fetch</h3><p>At its core, fetch only requires one argument: the location where it should send its request (which by default is a GET request). So if we wanted to access the <a href="https://swapi.co/">Star Wars API (SWAPI)</a> and find the fourth character in the database, we could use the following JavaScript code:</p><pre>const SWAPI_URL = &quot;<a href="https://swapi.co/api/people/4/">https://swapi.co/api/people/4/</a>&quot;;</pre><pre>fetch(SWAPI_URL)</pre><p>Running that code will execute without errors, but it won’t… well… <em>do</em> anything. Examining the result of this code in the terminal, we’re left with the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/568/1*PZMn3-uljo0mu_uoJj5R2w.png" /></figure><p>Our JavaScript has given us a <em>promise</em>. “Okay, I’ve sent a request to the server to GET information from the URL you gave me, and I promise I’ll do something with it.”</p><p>We haven’t told our program what to do with the request results, though, so let’s do that now. But first, there’s another step we have to deal with. SWAPI is formatted in JSON, as are many APIs. JavaScript Object Notation is text that <em>looks</em> like a JavaScript object when formatted properly, but it’s actually just a string. When the server gives us a string, we need to convert that into a JS Object that our program can actually use. Fortunately this is quite simple:</p><pre>fetch(SWAPI_URL)<br>.then(response =&gt; response.json() )</pre><blockquote>(For the sake of space we’re cutting out the actual SWAPI_URL assignment for the rest of this article, but just remember it’s the const defined in the first code snippet)</blockquote><p>Note that we use the name response inside the then call, but this is just convention and you can name it whatever you want. Common names also include resp, rsp, and r, as long as it’s clear what you’re doing in the code. When we execute this code and look at our console, we see the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/584/1*pY-Qa9wzK9u0qGsvuzOqUw.png" /></figure><p>Another promise! See a pattern emerging? Our JavaScript program is telling us, “Okay, I made a GET request to the server address you provided, I fulfilled my promise of turning that into a usable JavaScript Object, and now I promise I’ll do something else with that Object.” At this point, the world is our oyster! We have a usable JavaScript object, and we can do whatever we want with it! For starters, let’s just see what the object actually <em>is</em> that we’ve gotten back from the server:</p><pre>fetch(SWAPI_URL)<br>.then(response =&gt; response.json())<br>.then(result =&gt; {<br>    console.log(result)<br>});</pre><p>Again, the wordresult is just a name that we’ve chosen as shorthand for &quot;the usable Object converted from JSON we got back from the server&quot;. While using response for the initial fetch processing is fairly standard and intuitive, you might be working with all kinds of Objects for all kinds of reasons, so be careful in what name you use for the JSON-converted Object. It should be succinct, descriptive, and <em>accurate</em> to what the Object actually is. Let’s see what we have:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*GtFDZLBfaewcfgMeyxMdZQ.png" /></figure><p>Excellent! We receive another promise (which is what .then() does under the hood), but then that promise <em>resolves</em> with whatever instructions we put in the block. In this case, we’ve just printed the JS Object out to our console, but we can give it any kind of instructions we want. Let’s manipulate the DOM with our fancy new Object, this time giving it a more descriptive name:</p><pre>fetch(SWAPI_URL)<br>.then(response =&gt; response.json())<br>.then(darthVaderObj =&gt; {<br>  let name = document.createElement(&#39;h2&#39;);<br>  name.innerText = `Name: ${darthVaderObj[&#39;name&#39;]}`</pre><pre>let birth = document.createElement(&#39;h3&#39;);<br>  birth.innerText = `Born ${darthVaderObj[&#39;birth_year&#39;]}`</pre><pre>document.body.appendChild(name)<br>  document.body.appendChild(birth)<br>});</pre><p>Opening that in the browser results in the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*0pt23x2gpoQ6cPgS15Zkuw.png" /></figure><p>Voila! It may not look like much, but consider what just happened: someone else put this huge database of information on the internet, just raw information waiting to be used. In less than a dozen lines of code, we accessed that information and were able to tell our own program what to do with it. This is a simple example, but the implications are huge. As long as you can get the data from the server, you can do whatever you need to do with it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/767/0*58KL1irmwdaSOu81.jpg" /><figcaption>That said, don’t be too proud of this technological terror you’ve constructed. The ability to retrieve remote API data is insignificant next to the power of the Force.</figcaption></figure><p>Something worth noting: because .then() returns a promise, you have to do your work within the block of your fetch’s promise chain. If you try to assign a variable outside of the fetch, you get something like the following:</p><pre>let darth;</pre><pre>fetch(SWAPI_URL)<br>.then(response =&gt; response.json())<br>.then(darthVaderObj =&gt; {<br>  darth = darthVaderObj;<br>})</pre><pre>console.log(darth)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*9dR2PhyY5_oqedxyzvx8mQ.png" /></figure><p>Whomp. There are workarounds, but they’re kinda sloppy:</p><pre>let darth = [];</pre><pre>fetch(SWAPI_URL)<br>.then(response =&gt; response.json())<br>.then(darthVaderObj =&gt; {<br>  darth.push(darthVaderObj);<br>})</pre><pre>console.log(darth)</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*axu7VHyHt7DS2RJxSbdrBg.png" /></figure><p>It “works”, but you’re better off just doing the work you need to do inside the fetch promise.</p><h3>Moving beyond GET</h3><p>This is handy for getting data from an API, aka the R in CRUD, but what if we need to interact with the database in other ways? Where is C-UD? Good news, we can use that same fetch promise chain with relatively little additional complexity.</p><p>If we want to add additional data to the API or edit existing data, we need to tell the server what kind of request we’re making (POST or PATCH) and give it the actual data to add or change. Technically you can do this all in one giant chunk, but it’s easiest to assign the new API data (the body) to a variable, assign the HTTP request specifications (the config) to a variable, and give that to the fetch request in a nice, neat package. Let’s see what this looks like in action.</p><p>After a climactic battle over the forest moon of Endor, Darth Vader has gained redemption and returned to the light side of the Force as Anakin Skywalker. Before cremating his father’s body in a moving, John Williams-scored montage, Luke realizes he needs to send a PATCH request to update SWAPI appropriately.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*AJXcdqMO-Vya6zDN" /><figcaption>“Give me one second real quick while I update my package manager.”</figcaption></figure><p>First, he assigns the relevant changes to a variable:</p><pre>let bodyData= {&#39;name&#39;: &#39;Anakin Skywalker&#39;}</pre><p>Next, he sets up an object that tells the fetch() call what kind of HTTP request to make and how. Note the body line: we are converting the bodyData variable defined above from a JavaScript Object into a JSON string. This step is essential for the communication between our program and the server.</p><pre>let configObj = {<br>      method: &#39;PATCH&#39;,<br>      headers: {<br>        &quot;Content-Type&quot;: &quot;application/json&quot;,<br>        &quot;Accept&quot;: &quot;application/json&quot;<br>      },<br><strong>      body: JSON.stringify(bodyData)<br></strong>    };</pre><p>With these steps out of the way, it’s now actually quite simple for Luke to send his request to the server — he just gives this configuration Object to fetch() as an additional argument, letting it know to deviate from its default behavior.</p><pre>fetch(SWAPI_URL, configObj)</pre><p>Non-GET requests are a little bit more open-ended with what happens after we make them. By default, we just get an HTTP request code back from the server letting us know whether the operation succeeded or failed. Sometimes that’s all we need; for example, the following code would just print a message to our console based on the request status:</p><pre>fetch(SWAPI_URL, configObj)<br>.then(rsp =&gt; {<br>  if (rsp.ok) {<br>    console.log(&#39;Success!&#39;)<br>  }<br>})<br>.catch(error =&gt; console.log(error.message))</pre><p>We can imagine, however, that when editing an object within an API, we might want to get the edited object back for further work. This will require some editing of our backend behavior; for example, if we’re using Rails to build our API, we would need to add this final line to the update method in our relevant controller:</p><pre>render json:&lt;<strong>updated_object_name&gt;</strong></pre><p>Obviously, replace &lt;updated_object_name&gt; with the relevant variable name in your own program. This instructs update to send the modified object in JSON format back to the client once it’s finished executing. Once we receive the updated JSON, we can convert and manipulate it just like a normal GET request:</p><pre>fetch(SWAPI_URL, configObj)<br>.then(rsp =&gt; rsp.json())<br>.then(updatedObj =&gt; {<br>  <strong>console.log(updatedObj)</strong><br>})<br>.catch(error =&gt; console.log(error.message))</pre><p>In this case we’re just console logging the updated object, but we could manipulate and use it in any way we needed like we could with a standard fetch() request. This process would work pretty much exactly the same with a POST request. We would use a similar configObj for a DELETE request, but since they’re removing API information, they don’t take a body, and obviously can’t send an object back, so we’d just be customizing behavior based on a success/failure server response.</p><p>This just scratches the surface of using fetch(), but hopefully this examination of the basics will be useful in understanding the details as you delve into more specific uses for your own apps. Good luck, and may the Force be with you!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/602/0*UIWCk_YBaiJaAYx2" /><figcaption>Sebastian Shaw and Yub Nub or GTFO.</figcaption></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33a5f5d13fe0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The Siren Song of ‘has_and_belongs_to_many’ in Rails]]></title>
            <link>https://petehanner.medium.com/the-siren-song-of-has-and-belongs-to-many-in-rails-f526d6a6be79?source=rss-146710cad261------2</link>
            <guid isPermaLink="false">https://medium.com/p/f526d6a6be79</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Pete Hanner]]></dc:creator>
            <pubDate>Thu, 19 Sep 2019 14:27:38 GMT</pubDate>
            <atom:updated>2019-09-21T14:43:16.561Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/570/1*_sBynXIipkaSsB7QoS7CjQ.jpeg" /><figcaption>Beware! Read on to find out why.</figcaption></figure><p>As an object-oriented language, Ruby (and by extension, Rails) supports the use of classes to give context and functionality to the various object instances used throughout the program. These classes are all inter-related to each other in some way or another, and while many exist to model real-world objects, many exist only to store the relationship between those other classes. Rails, with its goal of making our programming lives as easy as possible, has provided an out-of-the-box way to create these model-linking models (called join tables) quickly and easily. That may sound tempting, but let’s dig into the reasons why the easiest path isn’t <em>always</em> the best.</p><h3>Join Tables: The Origin Story</h3><h4>Databases and many-to-many relationships</h4><p>In Ruby programming, relationships between our classes or models are discussed in terms of what other models they have and belong to, and whether those models are one or many. A one-to-many relationship (or has_many / belongs_to relationship in Ruby terms) is fairly simple. Imagine a museum full of paintings. A given artist may have dozens of paintings, but each painting belongs only to the one artist who painted it. When a painting is hung in the museum, a placard is placed below it listing who its artist is. Similarly, if we were to keep track of the gallery in a Rails program, we would just give our Painting model an artist_id column in its database migration. Thanks to Rails magic, all we have to do is assign a painting to an artist in the code, and ActiveRecord takes care of all the model linking behind the scenes.</p><p>It’s when we arrive at many-to-many relationships that things get thorny. To continue our painting example: the great masters often worked for many patrons, but each patron might have several painters as clients. If our program wants to track this relationship, we hit a problem. If an Artist wants to track all their Patrons in their own model, they would have to add a new column in the database table for any new patron, since databases can only store one piece of information per cell. As a popular artist grows in prosperity, we start to see the problem as columns forpatron1_id, patron2_id, patron3_id, patron4_id and so on gradually stretch across the page. This is true for all Artists, and the same holds for Patrons on the opposite side of the relationship.</p><p>The solution is the above-mentioned join table. This database table has just three columns: its own id, an Artist id, a Patron id (or whatever your many-to-many models happen to be). Without getting too deep into database concepts, this solves our problem by having a separate model that keeps track of every relationship between two other models — which as an added bonus is easier for a computer to search and filter. In Rails, we would just set up an ArtistPatron class and table in our migrations. From there, thanks to ActiveRecord magic again, we can assign or call things like michelangelo.patrons or lorenzo_medici.artists throughout our program, and the join table is updated or referenced automatically behind the scenes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/0*-S3N48k-IU0im7Yy.jpg" /><figcaption>Lisa approves.</figcaption></figure><h3>Join Tables Made Easy With Rails</h3><h4>Can you hear the sirens calling?</h4><p>Let’s imagine we’re writing a recipe app (like my wonderful partner Marisa and I were for Module 2 project week at Flatiron), where we want users to be able to add ingredients to their kitchen. Users will have many ingredients in their kitchens, and a given ingredient will appear in many users’ kitchens. Sounds like we need a join table! Let’s walk through the process, keeping in mind that this example glosses over or abridges some steps to focus on the relevant material.</p><p>First we set up the migrations:</p><pre>class CreateUsers &lt; ActiveRecord::Migration[6.0]<br>  def change<br>    create_table :users do |t|<br>      t.string :first_name<br>      t.string :last_name<br>      t.string :username<br>      t.timestamps<br>    end<br>  end<br>end</pre><pre>class CreateIngredients &lt; ActiveRecord::Migration[6.0]<br>  def change<br>    create_table :ingredients do |t|<br>      t.string :name<br>      t.integer :calories<br>      t.timestamps<br>    end<br>  end<br>end</pre><pre>class CreateUserIngredients &lt; ActiveRecord::Migration[6.0]<br>  def change<br>    create_table :user_ingredients do |t|<br>      t.integer :ingredient_id<br>      t.integer :user_id<br>      t.timestamps<br>    end<br>  end<br>end</pre><p>Once we’ve got our migrations up and running, then we wire up our relationships in the appropriate model files:</p><pre>class User &lt; ApplicationRecord<br>  has_many :user_ingredients<br>  has_many :ingredients, through: :user_ingredients<br>  ...</pre><pre>class Ingredient &lt; ApplicationRecord<br>  has_many :user_ingredients<br>  has_many :users, through: :user_ingredients<br>  ...</pre><pre>class UserIngredient &lt; ApplicationRecord<br>  belongs_to :user<br>  belongs_to :ingredient<br>  ...</pre><p>UGH! That’s so boring and takes so much time! All we <em>really</em> care about is the users and the ingredients, right? If the join table is just tracking the relationship between users and ingredients, isn’t there some way we could get rid of all the busy work in setting it up? Well as luck would have it, Rails provides <strong>just that very thing</strong>, in the form of thehas_and_belongs_to_many statement!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/0*1lVGq01H_OEfL4a7.jpg" /><figcaption>Oh hai.</figcaption></figure><p>Life is so much easier now! We just have to set up two migrations…</p><pre>class CreateUsers &lt; ActiveRecord::Migration[6.0]<br>  def change<br>    create_table :users do |t|<br>      t.string :first_name<br>      t.string :last_name<br>      t.string :username<br>      t.timestamps<br>    end<br>  end<br>end</pre><pre>class CreateIngredients &lt; ActiveRecord::Migration[6.0]<br>  def change<br>    create_table :ingredients do |t|<br>      t.string :name<br>      t.integer :calories<br>      t.timestamps<br>    end<br>  end<br>end</pre><p>… and only need to worry about two models to update, with even less code up top!</p><pre>class User &lt; ApplicationRecord<br>  has_and_belongs_to_many :ingredients<br>  ...</pre><pre>class Ingredient &lt; ApplicationRecord<br>  has_and_belongs_to_many :users<br>  ...</pre><p>That’s <em>soooooo </em>much cleaner, and easier for us as programmers to boot! Rails, being the smart cookie that it is, sees that has_and_belongs_to_many keyword and knows to create a join table behind the scenes, linking users and ingredients every time we associate any of their object instances</p><h3>But When Is a Join Table More Than a Join Table?</h3><h4>Lashing yourself to the mast</h4><p>Our recipe app is going great! Our users can add ingredients to their kitchen and properly keep track of their inventory. Let’s say we’ve even kept working and fleshed out our models by associating ingredients to individual recipes, giving recipes cuisine style tags and a rating system, let users sort recommended recipes based on ingredients they already have, and so on. Things are looking good, and now it’s time to implement our next feature! We want users to be able to mark certain ingredients as restricted, so any recipes using those ingredients get filtered out for them. This is a relationship between…</p><p>…hmmmm… this is a relationship between Users and Ingredients. But we’re already using the join table describing that relationship to keep track of a user’s kitchen items...? Okay, so we can’t set up another join table between those models, because it violates the single source of truth. Why don’t we just add a column to the user_ingredients table that keeps track of whether a user’s relationship to a given ingredient is “in kitchen” or “restricted?</p><p>Oh... Right. The user_ingredients table and its corresponding class model don’t exist. Because we got rid of them. Because we used has_and_belongs_to_many.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*xKCzBxWQycof9gJh.gif" /></figure><p>See why we shouldn’t do this?!? If we had just stuck with good old has_many :through, we wouldn’t be in this pickle! We could just fire up a new migration to add a column to the join table and be on our merry way! Now we have to roll our migrations <em>aaaaalllll</em> the way back and set up the model relationships from scratch.</p><p>Because, see, sometimes a join table isn’t just a join table. Sometimes — in fact, quite often — we want to keep track of extra data in that join model. Users might have different types of relationships with different ingredients. Movie tickets link customers to film showings, but also hold information like time, price, and location. Students have many classes and vice versa, but that relationship also has its own attributes like assignments and grades. Our painter-patron relationship from the top of the article also has attributes like what year the patronage began, which of an artist’s works were patronized by whom, and so forth. The examples are endless.</p><p>It’s also hard to know when a join table will stop being a join table and become a model in its own right. When we’re first starting a project and aiming only towards its <a href="https://blog.crisp.se/2016/01/25/henrikkniberg/making-sense-of-mvp">skateboard form</a>, it might seem like it makes sense to set up a join table the easy way. But as our projects grow, evolve, and add layers of complexity, we might realize our simple join table actually needs to be a full-fledged model to accomplish our goals.</p><p>There’s a tongue-in-cheek saying in software engineering that a programmer’s greatest virtue is their laziness, but there are even older proverbs to “look before you leap” and that “a stitch in time saves nine.” The saying about programmer laziness is <em>really</em> about the virtue of being creative in finding efficient solutions that accomplish a great deal without requiring intensive work. Rails’ implementation of has_and_belongs_to_many is an example of a solution that <em>seems</em> quick and easy, but will actually lead to more, harder work most of the time. That’s not the good kind of programmer laziness!</p><p>Just like Odysseus heard the alluring call of the sirens but knew well enough to lash himself to the mast lest he dash his ship against the rocks, we as programmers should know well enough to resist the tempting call of shortcuts and easier paths until we’re <em>one hundred percent sure</em> that they suit our situation and won’t end up creating more headaches in the long run. Go forth and code — carefully!</p><p>Maybe for my next blog post I can find a Rails metaphor for Scylla and Charybdis.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f526d6a6be79" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruby: Yielding, Enumerables, and You]]></title>
            <link>https://petehanner.medium.com/ruby-yielding-enumerables-and-you-9ab6a94eb5?source=rss-146710cad261------2</link>
            <guid isPermaLink="false">https://medium.com/p/9ab6a94eb5</guid>
            <category><![CDATA[bootcamp]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Pete Hanner]]></dc:creator>
            <pubDate>Thu, 22 Aug 2019 01:50:07 GMT</pubDate>
            <atom:updated>2019-08-22T01:50:07.600Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/622/1*t9ACO1FktYYSBQ3ewPVFOg.png" /></figure><p>When I started learning Ruby, I started noticing code snippets like the following:</p><pre>name_array.map { |name| name.upcase }</pre><p>or:</p><pre>name_array.find_all do |name|<br>  name.length &gt; 5<br>end</pre><p>What are those little pipes for? Where did the word inside the pipes come from? What’s that second part inside the curly braces or do-end statement? It kind of looks like a conditional, but I don’t see any if-else statements so it’s just sitting there on its own? <em>What is going on here???</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*0kpJNEwJgSpV5662Ck1RbQ.jpeg" /></figure><p>Okay, so I quickly found out that those are examples of enumerables — one of Ruby’s handiest features, and worth an entire separate discussion. But underneath the hood, what’s really at play is the <em>yield</em> keyword: deceptively simple in appearance, but very powerful, and possibly even handier than enumerables — after all, without yield, enumerables wouldn’t even exist.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*Luuy1cxYBuSDqE0QXET9DQ.gif" /></figure><h4>So what is yield?</h4><p>To understand yield, let’s look at an example first:</p><pre>def interrupting_cow<br>  puts &quot;Please let me talk without interrupting just for once.&quot;<br>  yield<br>  puts &quot;I don&#39;t know what I expected, you never listen.&quot;<br>end</pre><pre>interrupting_cow do<br>  puts &quot;MOO&quot;<br>end</pre><p>Running that code produces the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*u-yrX1TUKos210FEilK9hQ.png" /></figure><p>Let’s break it down:</p><p>First, we define a function interrupting_cow. It puts a statement to the terminal. Then, it uses that mysterious yield keyword. Finally, it puts out another statement.</p><p>Once the function is defined, we then actually call on it, using a do-end statement that puts out our iconic interrupting cow phrase. This do-end chunk (or { } if you’re writing a one-liner) is called a block.</p><p>The output of the function call shows us what’s going on with yield: The function runs normally and puts the first phrase. Then, when it hits yield, it jumps outside of the function and runs the code <em>inside the block</em> of the call (our interrupting cow says “MOO”). Once that code is done running, we jump back <em>into</em> the function and finish running the code there. So that’s yield in a nutshell — “Keep running until you hit me, but then <strong>stop</strong> and run all the code inside the block; once that’s done you can finish the function where you left off.”</p><h4>Optional blocks</h4><p>So now we’ve seen a very basic yield, but what if our ill-behaved cow is slowly learning some manners and only interrupts sometimes? Let’s try running the code below so she doesn’t say “MOO” while the farmer’s trying to talk:</p><pre>def maybe_interrupting_cow<br>  puts &quot;Please let me talk without interrupting just for once.&quot;<br>  yield<br>  puts &quot;Thank you for listening politely!&quot;<br>end</pre><pre>maybe_interrupting_cow</pre><p>Uh-oh! Trying to run that produces the following error message:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K9gc_NJknChp-3IXUVWN1Q.png" /></figure><p>The program puts out the first statement, but when we hit the yield, we get an error. By default, yield expects to be given a block, and errors out if that doesn’t happen. Fortunately, we can use the block_given? method to check on that. Let’s code a little logic into the conversation between our cow and farmer, then call the function once with a block and once without:</p><pre>def maybe_interrupting_cow<br>  puts &quot;Please let me talk without interrupting just for once.&quot;<br>  if <strong>block_given?</strong><br>    yield<br>    puts &quot;I don&#39;t know what I expected, you never listen.&quot;<br>  else<br>    puts &quot;...&quot;<br>    puts &quot;Thank you for listening politely!&quot;<br>  end<br>end</pre><pre>maybe_interrupting_cow do<br>  puts &quot;MOO&quot;<br>end</pre><pre>print &quot;\n&quot;</pre><pre>maybe_interrupting_cow</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/858/1*oc8kMDc_61s58w_FqMO_Ug.png" /><figcaption>(print “\n” in the code above is just to give us the line break in our output here)</figcaption></figure><p>Excellent! Our farmer can now react appropriately based on Bessie’s manners.</p><p><strong>Yielding with parameters</strong></p><p>We’ve seen how yield works at a basic level, and how to check if a block is given, but there’s one piece we’re missing that makes yielding so powerful: arguments. You can pass an argument to yield inside the method definition, and when you actually call the function, yield will in turn pass anything in your argument into the block — whatever the block happens to be. Blocks take block arguments, wrapped in braces | |, and can be named anything since they’re “anonymous,” or passed in from outside the block. If that sounds confusing, let’s look at a code example and its output:</p><pre>def cow_noise<br>  yield &quot;moo&quot; <br>end</pre><pre>cow_noise do |noise|<br>  puts &quot;The cow says #{noise}.&quot;<br>end</pre><pre>print &quot;\n&quot;</pre><pre>cow_noise do |noise|<br>  puts &quot;A duck does not say #{noise}.&quot;<br>end</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*XYxWzUTUIhreDpboacEymQ.png" /></figure><p>In the method definition, we’ve passed yield an argument of the string “moo.” In the method calls, we include a block argument called noise. We’ve given it that name, but it could be called anything (just be descriptive with your block arguments). We tell the method calls to puts a string and interpolate the block argument. But remember, the block argument noise is anonymous — It doesn’t do anything on its own, but rather gets the argument passed to yield in the method definition, and hands that off into the body of the block.</p><h4>Okay… so what’s the point of all this?</h4><p>If the code examples above seem abstract and maybe a little useless, well… it’s kind of because they are. That’s the trick with a lot of coding concept examples; they show what a feature <em>does</em> but not necessarily how it’s <em>used</em>. Let’s try and tie this together by showing the way yield functions under the hood of enumerables, that powerful Ruby feature we mentioned at the top.</p><p>All enumerables are built on the back of the each function. As a reminder, each looks like this:</p><pre>an_array.each do |item|<br>  # <em>some stuff to do to each item of the array<br></em>end</pre><p>You call each on an array* with dot notation, give a descriptive name for an individual member of that array in the block argument, and then <em>each</em> of those individual members is passed into the block to be manipulated by whatever code you’ve put there. each just works out of the box with Ruby, but what if we wanted to write our own version? Look at the code below with a comment above each line to explain what it’s doing.</p><blockquote>* Yes, you can call each on non-arrays too, but for the purposes of demonstration we’ll limit this discussion to arrays only.</blockquote><pre>def custom_each(array)<br><strong><em>  # check that user is using a block when calling method</em></strong><em><br></em>  if block_given?<br><strong><em>    # initialize counter</em></strong><em><br></em>    i = 0<br><strong><em>    #iterate over every item in the array</em></strong><em><br></em>    while i &lt; array.length<br><strong><em>      # whatever is in the block, do that to each successive array element<br></em></strong>      yield(array[i])<br><strong><em>      # increment counter<br></em></strong>      i += 1<br>    end<br><strong><em>    # return original array<br></em></strong>    array<br>  end<br>end</pre><p>By using a counter and ‘while’ loop, we can harness the power of yield to pass every member of a collection into a user-defined block:</p><pre>farm_animals = [&quot;cow&quot;, &quot;pig&quot;, &quot;goat&quot;, &quot;duck&quot;, &quot;horse&quot;]</pre><pre>farm_animals.each do |animal|<br>  puts animal<br>end</pre><pre>print &quot;\n&quot;</pre><pre>custom_each(farm_animals) do |animal|<br>  puts animal<br>end</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/164/1*S5wWa7bOnM9oB_RXOPd2tQ.png" /><figcaption>If you’re wondering why we call .each but custom_each(), it’s because #each is a method defined in the Enumerable module… which is a whole other discussion, so don’t worry about it for now.</figcaption></figure><p>Beautiful!</p><h4>Yield, each, and more advanced enumerables</h4><p>So each is pretty cool, but it’s 1) very generic, and 2) has a return value of the original array. It’s versatile, but not specialized. But Ruby gives us a whole module of enumerables to use, each with a particular use case, and each leveraging the power of each and yield under the hood. There’s a <em>ton </em>of them and it would take forever to look at each one, but let’s close this article out by taking a look at custom versions of the two all-star enumerables mentioned at the top: map (aka collect) and find_all (aka select).</p><p>We use map to make some change to every element of an array and return that changed array:</p><pre>def custom_map(array)<br><strong><em>  # check that user is using a block when calling method<br></em></strong>  if block_given?<br><strong><em>    #initialize new array for eventual return<br></em></strong>    new_array = []<br>   <strong><em> # whatever is in the block, do that to each successive array element and push it onto the new array</em></strong> <br>    array.each do |item|<strong><em><br></em></strong>      new_array &lt;&lt; yield(item)<br>    end<br><strong><em>    # return new array<br></em></strong>    new_array<br>  end<br>end</pre><p>We use find_all to go over every element of an array, returning a new array of only members meeting some criteria we define in the block:</p><pre>def custom_find_all(array)<br><strong><em>  # check that user is using a block when calling method<br></em></strong>  if block_given?<br><strong><em>    # initialize new array for eventual return<br></em></strong>    new_array = []<br><strong><em>    # look at every item in array<br></em></strong>    array.each do |item|<br><strong><em>      # only add item to return array if it evaluates &#39;true&#39; against block condition<br></em></strong>      if yield(item)<br>        new_array &lt;&lt; item<br>      end<br>    end<br><strong><em>    # return new array<br></em></strong>    new_array<br>  end<br>end</pre><p>Though you may not be using yield often in your own Ruby code, be aware that it’s still ever-present, hiding under the surface of every enumerable call. Hopefully these examples illustrate what a handy little tool it is, and maybe even inspire you to find some uses for it in your own custom methods.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9ab6a94eb5" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>