<?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 Violet Moon on Medium]]></title>
        <description><![CDATA[Stories by Violet Moon on Medium]]></description>
        <link>https://medium.com/@violetmoon?source=rss-34dd0115b2a2------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*eYm_H3sy-pnOUL0cP098nQ.jpeg</url>
            <title>Stories by Violet Moon on Medium</title>
            <link>https://medium.com/@violetmoon?source=rss-34dd0115b2a2------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 06:27:14 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@violetmoon/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[Refs: Manipulate the DOM in React.js]]></title>
            <link>https://medium.com/@violetmoon/refs-javascript-react-3b2c35ed30b?source=rss-34dd0115b2a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3b2c35ed30b</guid>
            <dc:creator><![CDATA[Violet Moon]]></dc:creator>
            <pubDate>Sat, 09 Feb 2019 00:06:36 GMT</pubDate>
            <atom:updated>2019-02-12T22:14:49.053Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KneUR7IQoCLNY9go" /><figcaption>Photo by <a href="https://unsplash.com/@sapegin?utm_source=medium&amp;utm_medium=referral">Artem Sapegin</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p><strong>Refs provide a way to access, select or manipulate a DOM node within a React component without passing props or re-rendering the component.</strong></p><p>Traditionally, this process can be accomplished using an ID. If you are referencing an HTML element once, this is solution works fine. But what would happen if you wanted to render a child component multiple times with each components attributes contained to itself? This is where IDs prove troublesome.</p><p>To preface, I won’t be going into detail differentiating IDs from refs. However, if you’d like an explicit (and <em>brief) </em>example illustrating the difference, here’s an excellent use case:</p><p><a href="https://www.javascriptstuff.com/use-refs-not-ids/">Why to use refs instead of IDs</a></p><h3>Controlled vs. Uncontrolled Components</h3><p>Controlled components ensure that the parent manages and provides the prop and state values by notifying changes through callbacks like the event handler. In example below, the input value is readily accessible throughout the component without needing the value to be explicitly extracted from the input element.</p><pre>class Controlled extends React.Component {<br> state = { input: &#39;&#39; }</pre><pre>handleChange = (event) =&gt; {<br>  this.setState({input: event.target.value})<br> }</pre><pre>render() {<br>  return (<br>   &lt;div&gt;<br>    &lt;div&gt;{this.state.input}&lt;/div&gt;<br>    &lt;input <br>     type=&#39;text&#39;  <br>     value={this.state.input} <br>     onChange={this.handleChange}<br>     /&gt;<br>   &lt;/div&gt;<br>  )<br> }<br>}</pre><p>Uncontrolled components harness the power of refs to query the DOM for node values directly by storing their own state locally. This means two things. First, uncontrolled components function similarly to traditional HTML. <strong>Second, refs manipulate the DOM directly.</strong></p><pre>class Uncontrolled extends React.Component {<br> <br> state = {<br>  input: &#39;&#39;<br> }<br>  <br>  onSubmit = event =&gt; {<br>   event.preventDefault()<br>     this.setState({ input: this.input.value })<br> }</pre><pre>render() {<br>  return (<br>   &lt;div&gt;<br>    &lt;div&gt;{this.state.input}&lt;/div&gt;<br>    &lt;form onSubmit={this.handleSubmit}&gt;<br>     &lt;input type=&#39;text&#39; ref={el=&gt; this.input = el}/&gt;<br>     &lt;button&gt;click here&lt;/button&gt;<br>    &lt;/form&gt;<br>   &lt;/div&gt;<br>  )<br> }<br>}</pre><p>I have found understanding the fundamental differences in uncontrolled versus controlled components has become helpful when deciding whether a particular use case demands a localized state and directly modify the DOM to accomplish my goal, or if it is possible to lean on the child’s parent.</p><h3>Why Refs?</h3><p>Whether an instance of a React component or a DOM element, refs provide a way to modify a child component outside of a standard parent-to-child prop pass. Meaning, in situations where you want to apply specific modifications to an element without triggering a component re-render, refs have your back.</p><p>The official React <a href="https://reactjs.org/docs/refs-and-the-dom.html">docs</a> provide three example scenarios in which you could potentially want implement a ref into your React project:</p><ol><li>Managing <strong>focus, text selection, or media playback</strong>.</li><li>Triggering imperative <a href="https://stackoverflow.com/questions/51223592/triggering-imperative-animations-using-react-refs"><strong>animations</strong></a>.</li><li>Integrating with third-party <a href="https://reactjs.org/docs/integrating-with-other-libraries.html"><strong>DOM libraries</strong></a>.</li></ol><p>In the examples below, I am going to detail how to incorporate refs when wanting to focus, select text or playback media — using one of three methods for creating refs: 1) String Refs, 2) Callback Refs, and 3) React.createRef.</p><h3>Example 1: String + Media Playback</h3><p>Although this method will most likely be deprecated in a future React release, <em>string refs </em>are the oldest way of writing refs, and could potentially be helpful for understanding a traditional ref use cases.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AD5ZWD6eTB0fkVdUHYjK1A.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fu47zCyYfp5jXgVfC3V%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fu47zCyYfp5jXgVfC3V%2Fgiphy.mp4&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fu47zCyYfp5jXgVfC3V%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/ec376577dfad17278e934c3f8d819d4b/href">https://medium.com/media/ec376577dfad17278e934c3f8d819d4b/href</a></iframe><h3>Example 2: Callback + Text Selection</h3><p>Instead of passing a string, a <em>callback ref </em>asks you to add an inline callback function that accepts a component-wide accessible DOM node or instance as an argument.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-JLBeQmfa4l7iJYJWspUbQ.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F5n2ai9YPeZqVl74TY5%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F5n2ai9YPeZqVl74TY5%2Fsource.mp4&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F5n2ai9YPeZqVl74TY5%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="217" frameborder="0" scrolling="no"><a href="https://medium.com/media/01c532fb7e565311fa462f9a8b1ab8d4/href">https://medium.com/media/01c532fb7e565311fa462f9a8b1ab8d4/href</a></iframe><p>Another super helpful tidbit…</p><blockquote>When using inline callback refs like we did in our example, it is important to know that for every update to the component, the callback function is called twice. First with null, then again with the DOM element.</blockquote><blockquote>However, creating the callback function as a bound method of the component class can be used to avoid this behavior. — <a href="https://medium.com/u/ddcd0e9719e5">Glad Chinda</a></blockquote><h3>Example 3: Create + Focus</h3><p>React.createRef the newest (and personally-considered simplest method) for creating refs. After setting your React.createRef(), you attach your ref attribute to the DOM node you’d like to manipulate. Referring to the ref value is as simple as calling this.myCreatedRef.current.value whenever you need render the updated value.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*aWsJwNsO9Q-4-j8FU0XUnA.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FcttHaFWXkZUBGiY4XR%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FcttHaFWXkZUBGiY4XR%2Fgiphy.mp4&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FcttHaFWXkZUBGiY4XR%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/266bc120495d7a0cfe26ac1157f1f9ac/href">https://medium.com/media/266bc120495d7a0cfe26ac1157f1f9ac/href</a></iframe><h3>Additional Ref-sources</h3><ul><li><a href="https://blog.logrocket.com/how-to-use-react-createref-ea014ad09dba">How to use React createRef</a></li><li><a href="https://www.fullstackreact.com/articles/using-refs-in-react/">Fullstack React: Fullstack React&#39;s Guide to using Refs in React Components</a></li><li><a href="https://medium.com/@mrewusi/a-gentle-introduction-to-refs-in-react-f407101a5ea6">A gentle introduction to Refs in React</a></li><li><a href="https://css-tricks.com/working-with-refs-in-react/">Working with refs in React | CSS-Tricks</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3b2c35ed30b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Dev Resources]]></title>
            <link>https://medium.com/@violetmoon/dev-resources-715dcec6895b?source=rss-34dd0115b2a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/715dcec6895b</guid>
            <category><![CDATA[design]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[linux]]></category>
            <category><![CDATA[front-end-development]]></category>
            <dc:creator><![CDATA[Violet Moon]]></dc:creator>
            <pubDate>Fri, 01 Feb 2019 03:57:07 GMT</pubDate>
            <atom:updated>2019-02-03T02:44:12.657Z</atom:updated>
            <content:encoded><![CDATA[<p>Although initially intended for personal reference, I thought perhaps some or all of these could be of use to the expanding dev community. I will continue to add relevant coding materials here as they prove practical, fascinating, supportive or any combination of the three.</p><h3><strong>Dual-boot Dell XPS-15 with Linux</strong></h3><p><a href="https://medium.com/@pwaterz/how-to-dual-boot-windows-10-and-ubuntu-18-04-on-the-15-inch-dell-xps-9570-with-nvidia-1050ti-gpu-4b9a2901493d">https://medium.com/@pwaterz/how-to-dual-boot-windows-10-and-ubuntu-18-04-on-the-15-inch-dell-xps-9570-with-nvidia-1050ti-gpu-4b9a2901493d</a></p><p><a href="https://github.com/rcasero/doc/wiki/Ubuntu-linux-on-Dell-XPS-15-(9560)">https://github.com/rcasero/doc/wiki/Ubuntu-linux-on-Dell-XPS-15-(9560)</a></p><h3><strong>Dis/enable Touchscreen</strong></h3><p>Command Line: xinput disable or xinput enable + appropriate #</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hYjq-nj5Iod0A4ghh9I1NA.png" /></figure><h3><strong>Increase inotify Watchers</strong></h3><p><a href="https://github.com/guard/listen/wiki/Increasing-the-amount-of-inotify-watchers">https://github.com/guard/listen/wiki/Increasing-the-amount-of-inotify-watchers</a></p><h3><strong>Kill Port</strong></h3><p><a href="https://stackoverflow.com/questions/11583562/how-to-kill-a-process-running-on-particular-port-in-linux">https://stackoverflow.com/questions/11583562/how-to-kill-a-process-running-on-particular-port-in-linux</a></p><h3><strong>Command Line Aliases</strong></h3><p><a href="https://www.hostingadvice.com/how-to/set-command-aliases-linuxubuntudebian/">https://www.hostingadvice.com/how-to/set-command-aliases-linuxubuntudebian/</a></p><h3><strong>Design Inspiration</strong></h3><p><strong>Profile</strong></p><ul><li><a href="https://medium.com/inspiration-supply/profile-page-design-inspiration-31878d23f906">https://medium.com/inspiration-supply/profile-page-design-inspiration-31878d23f906</a></li><li><a href="https://medium.muz.li/50-user-profile-page-design-inspiration-5c45aeeda400">https://medium.muz.li/50-user-profile-page-design-inspiration-5c45aeeda400</a></li><li><a href="https://medium.muz.li/profile-page-inspiration-2152f16bde07">https://medium.muz.li/profile-page-inspiration-2152f16bde07</a></li></ul><p><strong>Landing</strong></p><ul><li><a href="https://medium.com/collect-ui-design-ui-ux-inspiration-blog/landing-page-inspiration-march-2018-a86499f930f">https://medium.com/collect-ui-design-ui-ux-inspiration-blog/landing-page-inspiration-march-2018-a86499f930f</a></li></ul><p><strong>Forms</strong></p><ul><li><a href="https://medium.muz.li/form-design-inspiration-6bb9a350f2d8">https://medium.muz.li/form-design-inspiration-6bb9a350f2d8</a></li></ul><p><strong>General</strong></p><ul><li><a href="https://www.pinterest.com/dreamingmao/ui-layout/?lp=true">https://www.pinterest.com/dreamingmao/ui-layout/?lp=true</a></li></ul><h3><strong>Medium</strong></h3><p><strong>@frontendweekly→ </strong><a href="https://medium.com/front-end-weekly">https://medium.com/front-end-weekly</a></p><p><strong>@RyanFlorence→ </strong>https://medium.com/@ryanflorence</p><p><strong>@MelissaMcewen</strong> → <a href="https://medium.com/@melissamcewen">https://medium.com/@melissamcewen</a></p><h3><strong>YouTube</strong></h3><p><strong>Fun Fun Function: </strong><a href="https://www.youtube.com/channel/UCO1cgjhGzsSYb1rsB4bFe4Q">https://www.youtube.com/channel/UCO1cgjhGzsSYb1rsB4bFe4Q</a></p><p><strong>Kevin Powell: </strong><a href="https://www.youtube.com/channel/UCJZv4d5rbIKd4QHMPkcABCw">https://www.youtube.com/channel/UCJZv4d5rbIKd4QHMPkcABCw</a></p><p><strong>React Conference: </strong><a href="https://www.youtube.com/channel/UCz5vTaEhvh7dOHEyd1efcaQ">https://www.youtube.com/channel/UCz5vTaEhvh7dOHEyd1efcaQ</a></p><p><strong>Pink Floyd: </strong><a href="https://www.youtube.com/channel/UCY2qt3dw2TQJxvBrDiYGHdQ">https://www.youtube.com/channel/UCY2qt3dw2TQJxvBrDiYGHdQ</a></p><p><strong>Radiohead: </strong><a href="https://www.youtube.com/channel/UCq19-LqvG35A-30oyAiPiqA">https://www.youtube.com/channel/UCq19-LqvG35A-30oyAiPiqA</a></p><h3>Testing</h3><p><strong>Enzyme: </strong><a href="https://devhints.io/enzyme">https://devhints.io/enzyme</a></p><h3><strong>React/Redux</strong></h3><p><strong>Redux:</strong> <a href="https://redux.js.org/basics/usage-with-react">https://redux.js.org/basics/usage-with-react</a></p><p><em>If there’s a resource you have found particular helpful, definitely let me know in the comments below. I would love to check it out.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=715dcec6895b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[From Ruby to Node + Express]]></title>
            <link>https://medium.com/@violetmoon/from-ruby-to-node-express-sample-project-35673c3860a8?source=rss-34dd0115b2a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/35673c3860a8</guid>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[developer]]></category>
            <category><![CDATA[cats]]></category>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[projects]]></category>
            <dc:creator><![CDATA[Violet Moon]]></dc:creator>
            <pubDate>Fri, 25 Jan 2019 07:24:26 GMT</pubDate>
            <atom:updated>2019-01-25T19:39:09.335Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*KNmKfXGwnrCsGPRn" /><figcaption>Photo by <a href="https://unsplash.com/@nrly?utm_source=medium&amp;utm_medium=referral">Nathan Riley</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>I have always identified as more cat than dog. There is a mutual respect, an understanding between myself and the domesticated feline community. Exchanging glances with an independent, misanthropic stray is like noticing someone listening to my favorite album — it supplies that<em> “I get you, you get me”</em> comfort. The difference, however, is that while curiosity keeps killing cats, my curiosity-driven nature has had better evolutionary luck.</p><p>As a Ruby-based programmer, I have implemented and deployed several full stack Ruby on Rails apps for a number of self-betterment projects. Nevertheless, curiosity has a remarkable way of cultivating continued learning, and with this came the drive to explore an additional language.</p><p>Although a JavaScript veteran, I was new to the back end ecosystem. Naturally, hundreds of questions surfaced as I leapt into foreign lands: <em>What is Node? How do I implement it? Does Node have gems? How do I build RESTful API routes? Can and how do I connect a database? Which ORMs work with Node?</em> Several months and full stack deployments later, I began confidently sharing with other humans (and cats) that I am also a Node-based programmer.</p><p>And this is my transitional guide…</p><h3><strong>What is Node?</strong></h3><p><em>Node is a javascript-based platform</em> designed to support intensive input/output and event-driven web applications. Respectively, it is made up of two parts: runtime environment and JavaScript library. The runtime environment being the data types and functions inherent to JavaScript (like arrays, strings and `setInterval()` for example). JavaScript library includes modules packaged into Node, meaning you don’t need `npm install` prior to `require`ing it into your application. You can check those out <a href="https://nodejs.org/api/index.html">here</a>.</p><h3><strong>What is Express?</strong></h3><p><em>Express is a node.js web framework </em>that provides a robust set of features for developing web and mobile applications, according to the <a href="https://expressjs.com/">docs</a>. The purpose is to provide fast, minimal and un-opinionated web app features without destructing Node’s fundamental capabilities. Express does this through a myriad of HTTP utility methods, middleware implementation and dynamically rendering HTML pages to the browser.</p><h3><strong>If not gems, then what?</strong></h3><p>RubyGems is to Ruby as NPM is to Node. Both serve as package managers developed and maintained by their corresponding developer community. So just like you would `gem install some-library`, you would `npm install some-library`.</p><h3><strong>Where do I start?</strong></h3><p>Follow the steps below! — and I also recommend meandering through the basic quick-start documentation. I completely recognize that this is frequently the least helpful suggestion, especially in response to a specific question. However, seeing as this is a general introduction, the sample guides for each (<a href="https://nodejs.org/en/about/">Node</a> + <a href="https://expressjs.com/en/guide/routing.html">Express</a>) are an excellent resource to begin acquainting yourself with the syntax/structure and later refer back to for clarification.</p><h3><strong>How do I build a sample app?</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*NrPS4QCwzKcZ_2AK-J2e0g.png" /></figure><p>For this short demo, we’re building catjective: find your kind of cat. We will be creating two routes, incorporating a fetch request to Giphy API, and then rendering the JSON data to the DOM. If you want to skip the following steps or clone to follow along, here is <a href="https://github.com/vio1337/node-catjective">the repo</a>. Ironic but in case you don’t want to search for an additional cat, the repo also has a cat image you can render for the logo.</p><p><strong><em>To run the server after creating the server.js and index.html files: go to your terminal and type </em></strong><strong>node server.js<em> from inside your project folder.</em></strong></p><h3><strong>Set up + Config</strong></h3><pre><strong>1.</strong> Install Node + NPM: <a href="https://linuxize.com/post/how-to-install-node-js-on-ubuntu-18.04/"><strong>Linux</strong></a><strong> || </strong><a href="http://osxdaily.com/2018/06/29/how-install-nodejs-npm-mac/"><strong>Mac</strong></a><strong> || </strong><a href="https://treehouse.github.io/installation-guides/windows/node-windows.html"><strong>Windows</strong></a></pre><pre><strong>2.</strong> Grab yourself a <a href="https://developers.giphy.com/"><strong>Giphy API key</strong></a> by signing up + clicking create an app.</pre><pre><strong>3.</strong> Create a new app folder: <br><strong>mkdir node-catjective</strong></pre><pre><strong>4.</strong> Inside your main directory, create a public folder and a server: <strong>mkdir public<br>touch server.js .env</strong></pre><pre><strong>5.</strong> In the public folder, create a JavaScript + HTML file: <br><strong>touch index.js index.html</strong></pre><pre><strong>6.</strong> Add npm to enable dependency integration later: <br><strong>npm init</strong></pre><pre><em>+ For the case of this sample app, you can just press enter when each question appears.</em></pre><pre><strong>7.</strong> Add Express, fetch and dotenv: <br><strong>npm i express node-fetch dotenv --save</strong></pre><pre><strong><em>+ </em></strong><a href="https://www.npmjs.com/package/node-fetch"><strong><em>node-fetch</em></strong></a><em> is just one of many alternatives to making an API request and what I will be using in the example below</em></pre><pre><strong><em>+ </em></strong><a href="https://www.npmjs.com/package/dotenv"><strong><em>dotenv</em></strong></a><strong><em> </em></strong><em>allows you to store environment variables in a </em><em>.env file so that you can have access to them through </em><em>process.env.ENV_VAR_NAME</em></pre><pre>8. Open folder in text editor.</pre><h3>.env</h3><p>The only thing you need to put in the .env file is your API key, like so:</p><pre>API_KEY=_____paste your api key here______</pre><h3><strong>server.js</strong></h3><p>The server.js file is where you will house all of your Node and Express elements for this project. Below is the entirety of what we will put in the file. I wanted to provide a cohesive visual before fragmenting the code to explain each part in greater detail.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yEHo51i27aIy2nLqbUdUYw.png" /></figure><p>These four variables are where you’ll import Express and several route helpers to run the server; they all consist of your basic setup.</p><pre>const express = require(&#39;express&#39;)<br>const app = express()<br>const path = require(&#39;path&#39;)<br>const router = express.Router()</pre><p>Now you’ll require dotenv and fetch so the project has global access to both.</p><pre>require(&#39;dotenv/config&#39;)<br>const fetch = require(&#39;node-fetch&#39;)</pre><p>Next step is to set up the host and port so the server knows where to run.</p><pre>const hostname = &#39;0.0.0.0&#39;<br>const port = 2020</pre><p>Below is a concatenated version of the Giphy API request. It is separated into two parts (head and tail) so that after a user inputs an adjective into the search query, we can make a fetch request with their input value. The urlTail also has the API_KEY env variable we established at the beginning.</p><pre>const urlHead = &#39;http://api.giphy.com/v1/gifs/search?q=&#39;<br>const urlTail = `+cat&amp;api_key=${process.env.API_KEY}&amp;limit=20`</pre><p><strong>This is our first route. </strong>Node has several <a href="https://expressjs.com/en/guide/routing.html">response methods</a> that allow you to redirect, prompt a download, render static files (like below) and 5+ more options. Here we are using res.sendFile and path to point and render the index.html page from the parent directory.</p><pre>router.get(&#39;/&#39;, (req, res) =&gt; {<br>    res.sendFile(path.join(__dirname,&#39;/public/index.html&#39;))<br>})</pre><p><strong>This is our Giphy API request route. </strong>We are using async/await and fetch to create the API request. Say a user inputs the catjective hairy, we can take that input and make a fetch request with the route localhost:2020/hairy and have it return an array of gifs. This allows us to simplify the code we write in our JavaScript file later.</p><pre>router.get(&#39;/:catjective&#39;, async (req, res) =&gt; {<br> let r = await fetch(urlHead + req.params.catjective + urlTail)<br> let jsonCats = await r.json()<br> let cats = jsonCats.data.map(c=&gt; c.images.fixed_height.url)<br> res.json(cats)<br>})</pre><p>We’re using router middleware (an express routing system) because its modular and designed to support route handlers. If, for example, we built our own API and wanted to preface every route with /api/vi/ . We would then need to add app.use(&#39;/api/vi/&#39;, router) to our sever so that we could just write a set of RESTful routes like so:</p><ul><li>router.get(&#39;/cats&#39;), router.post(&#39;/cats&#39;), router.put(&#39;/cats/:id&#39;) or router.delete(&#39;/cats/:id&#39;)</li></ul><p>Then, it would simply fetch localhost:2020/api/v1/cats or /cats/1 for us. The second app.use() enables us to render static files throughout the project. By adding &#39;public&#39; to the function, the server now knows to look in the public folder at the root directory for our static HTML, png and JS file.</p><pre>app.use(&#39;/&#39;, router)<br>app.use(&#39;/public&#39;, express.static(&#39;public&#39;))</pre><p>These last two lines create a server, run it on our port 2020, and console.log our terminal — to provide a visual cue that our server is running.</p><pre>app.listen(process.env.port || port)<br>console.log(`Witchcraft on aisle ${hostname}:${port}`)</pre><h3><strong>index.html</strong></h3><p>This is the HTML template that renders on our root route: localhost:2020</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JqnW9SENuSQnVC1No1qTSg.png" /></figure><h3>index.js</h3><p>Here is the JavaScript that allows us to grab the user’s catjective, make a fetch request to our /:catjective route, and then render the response to the DOM.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_3jVxPNAtv0Yx8P0CDFREQ.png" /></figure><h3>styles.css</h3><p>As with <em>most</em> styling, the CSS below is added to simply make it look better.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PRWMPFln2AZZbhsSdjXoWQ.png" /></figure><h3><strong>But what about databases and ORMs?</strong></h3><p>In an upcoming blog, I will dive into explicit, step-by-step detail on how to create a RESTful API using Postgres and Sequelize as well as alternative database and ORM options. Until then, the <a href="http://docs.sequelizejs.com/">Sequelize</a> documentation is of particularly high quality and worth a read.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=35673c3860a8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Fetch + Render Instagram Media]]></title>
            <link>https://medium.com/@violetmoon/fetch-render-instagram-media-a75b1610dc53?source=rss-34dd0115b2a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/a75b1610dc53</guid>
            <category><![CDATA[expressjs]]></category>
            <category><![CDATA[instagram]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Violet Moon]]></dc:creator>
            <pubDate>Sun, 13 Jan 2019 23:30:27 GMT</pubDate>
            <atom:updated>2019-01-25T23:42:47.783Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*nYVRwTKO1qURZQjs" /><figcaption>Photo by <a href="https://unsplash.com/@thoughtcatalog?utm_source=medium&amp;utm_medium=referral">Thought Catalog</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>If you have ever tried fetching or scraping your Instagram profile, you probably have simultaneously been presented with the agonizing OAuth hoops — through which you are required to jump if you want a JSON API of your Instagram account.</p><p>From a security perspective, this is reassuring. The mandatory clearance prior to granting detailed access to personal data provides some level of comfort because it ensures there is a record of every account wanting to obtain the company’s client’s content.</p><p>From a developer perspective, I resented the hoops. In resonance with many of my technical peers however, I enjoy exercising great mental power to derive simpler solutions. So like two six-year-olds duking it out over who goes down the big slide first, this Instagram process provoked: <em>do you really think you can make this easy?</em></p><p>My rebuttal? <em>Of course.</em></p><p>Whether educational, personal or curiosity driven, hopefully the following steps alleviate <em>some of</em> the headache accompanied with accessing your Instagram data.</p><h3><strong>Step 1</strong></h3><p><a href="http://instagram.com/">Sign in</a> to your Instagram account from your desktop.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/869/0*KwPw4Lq1KxcO291i" /></figure><h3><strong>Step 2</strong></h3><p>Go to Instagram’s developer hub. You can do that via google or just <a href="https://www.instagram.com/developer/">click here</a>. The landing page should look like the image below. Once arriving, click <em>Register Your Application.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/843/0*iIld-XO0cMKS1J7K" /></figure><h3><strong>Step 3</strong></h3><p>In the top right corner of your screen, click the green button that says <em>Register a New Client</em>. This should take you to a page that looks like this…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/873/1*GHx3Cs4KuIPoFmxu7J46zg.jpeg" /></figure><p>For this next portion, I used a service called <a href="https://elfsight.com/">Elfsight</a>, which served as a free redirect landing page so that, instead of authenticating through your web app, you can just grab your profile’s API.</p><p>Now, I am relentlessly suspicious granting third-party-apps permission to my data. But after reading Elfsight’s <a href="https://elfsight.com/privacy-policy/">privacy policy</a>, there was little difference in what they would gain access when to compared to what was already available on a public profile. You can also revoke access from any third-party app at any time under your profile page by clicking the settings icon, then <em>Authorized Apps</em>.</p><p>If this doesn’t feel good to you, there are Instagram plugins like <a href="http://instafeedjs.com/">Instafeed.js</a> and <a href="http://spectragram.js.org/">Spectragram.js</a> (plus a <a href="https://www.sitepoint.com/5-instagram-jquery-plugins/">few more</a>) that provide simple API media rendering.</p><h3><strong>Step 4</strong></h3><p>Fill out the form — Application Name, Description, Website URL and Valid redirect URIs are the only required fields.</p><p>The official post for integrating Elfsight mentioned filling in the <em>Website URL </em>and the <em>Valid redirect URIs </em>field with the the following web address:</p><p><a href="https://elfsight.com/service/generate-instagram-access-token/"><strong>https://elfsight.com/service/generate-istagram-access-token</strong></a><a href="https://elfsight.com/service/generate-instagram-access-token/">/</a></p><p>However, I added it only to the <em>Valid redirect URIs </em>field and the outcome was the same. So regarding which to do, the choice is yours.</p><h3><strong>Step 5</strong></h3><p>Once you click the green<strong> </strong><em>Register </em>button, you will be directed back to the main app portal, which should look something like the image below. Once here, click the <em>Manage </em>button.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/756/0*wiwqMV6_RqqoY1DA" /></figure><h3><strong>Step 6</strong></h3><p>Make sure your app’s portal page has a Client ID and Client Secret. You’ll need both for the next step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/881/0*O2bovN6OWHPfWpr4" /></figure><h3><strong>Step 7</strong></h3><p>Open a new tab with <a href="http://elfsight.com/service/generate-instagram-access-token/">this link</a> to Elfsight. The landing page will have two fields: one for your Client ID and the other for your Client Secret. Now go wild and copy/paste those guys.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/914/0*hmNrXUH5oWkNrNe7" /></figure><h3><strong>Step 8</strong></h3><p>Authorize and save your new access token in a text editor.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/723/0*gETNauBPawLf1uux" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/0*RYtkjhtmUN1xYCHU" /></figure><p>Now that you have your access token, in the following section I am going to go over how to render your content to your website. For my particular use case, I wanted to render a basic HTML template for an email campaign with the media from my Instagram business profile.</p><p>For an overall glance, feel free to sift through the <a href="https://github.com/vio1337/insta-parser">Github</a> repo — or clone it and manipulate it to your specific use case.</p><h3><strong>Step 9</strong></h3><p>Open your terminal and mkdir new-app.</p><h3><strong>Step 10</strong></h3><ul><li><strong>a. </strong>In your new-app folder, touch index.html index.js, then npm init</li><li><strong>b.</strong> If you want make an HTTP request in Node using http, <a href="https://codeburst.io/how-to-make-an-http-request-in-nodejs-http-mechanism-libraries-f25ec990d307">this article</a> has a nice breakdown and the <a href="https://nodejs.org/api/http.html">docs</a>. If you want to use fetch (I use fetch in the example below), you’ll want to also npm install --save node-fetch or yarn add node-fetch.</li><li><strong>c. </strong>If you’re uploading your code to a public repository (like Github) and want to keep your access token hidden, we will create some environment variables by npm install --save dotenv or yarn add dotenv. You will also want to create two files in the app’s parent directory: .gitignore and .env</li></ul><h3><strong>Step 11</strong></h3><p>In the .gitignore file, on two separate lines add: node_modules and .env</p><h3><strong>Step 12</strong></h3><p>In the .env file, create an all caps global variable name. Something clever like TOKEN will do. If you’re like me and need incredibly explicit instruction, it should look something like…</p><p>TOKEN = 09u3094u3.aCcESstOKen.02748d8w7.morerandomness</p><h3><strong>Step 13</strong></h3><p>Next, open the index.js in your text editor and add the following code…</p><pre>// allows access to fetch<br>const fetch = require(‘node-fetch’)</pre><pre>// enables the use of env variables <br>require(‘dotenv/config’)</pre><pre>// make your fetch request with your access token<br>fetch(`https://api.instagram.com/v1/users/self/media/recent/?access_token=${process.env.TOKEN}`)</pre><pre>.then(r=&gt; r.json())<br>.then(r=&gt; r.data)<br>.then(r=&gt; {</pre><pre>// renders the 9 most recent posts<br>let obj = {}<br>for (let i=0; i&lt;=8; i++) {<br>obj[r[i].images.standard_resolution.url] = r[i].link<br>}<br>return obj<br>})</pre><pre>.then(r=&gt; {</pre><pre>// this generates the HTML I want to paste into my email campaign<br>let html = Object.keys(r).map((x)=&gt; {<br>return `&lt;a href=”${r[x]}”&gt;&lt;img class=”insta-pic” src=”${x}”/&gt;&lt;/a&gt;`<br>})<br>console.log(html)<br>})</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/925/1*6PHLcXiti2139y0M-4ftgA.png" /><figcaption>same as the code above— not copy/paste-able but moderately more aesthetic (and readable)</figcaption></figure><p><strong>Step 13. </strong>Running node index.js spits out the code below, which I then, (1) copy/pasted into index.html file to initially create a basic styling and rendering template, so that I could later (2) copy/paste the console.log(html) output directly into my email campaign.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*e923z2vnk9ob6CXMZ3WxRw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*zym6BMmM7qcHPEHZjo7tWw.png" /><figcaption><em>terminal output and sample html template to add to an email campaign</em></figcaption></figure><p><strong>Fun tip:</strong> Mailchimp has an <a href="https://templates.mailchimp.com/resources/inline-css/">inline CSS styler</a> that allows you to turn the above html template into inline styling — convenient for when you don’t want to write the same 20-something characters 9+ times.</p><p>And that’s it! If you have any questions or suggestions, please feel free to drop them below. Thanks for reading and may your coding adventures consist of minimal, literal head-banging (and many of the <em>70s rock </em>sorts).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a75b1610dc53" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Router + Portfolio Template.]]></title>
            <link>https://medium.com/@violetmoon/react-router-portfolio-template-3105d54f0525?source=rss-34dd0115b2a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3105d54f0525</guid>
            <category><![CDATA[react-router]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[template]]></category>
            <category><![CDATA[router]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Violet Moon]]></dc:creator>
            <pubDate>Tue, 13 Nov 2018 16:13:27 GMT</pubDate>
            <atom:updated>2018-12-17T08:26:50.914Z</atom:updated>
            <content:encoded><![CDATA[<p><strong><em>In case you’re here solely for the template, </em></strong><a href="https://github.com/vio1337/routes-template"><strong><em>here</em></strong></a><strong><em>. I understand having a strong distaste for excessive scrolling, so please enjoy this scroll-free.</em></strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/951/1*gwNAFGfrENqAY0pSixeN3Q.png" /></figure><h3>If you’re starting from nothing.</h3><p>To get started, create a basic react app npx create-react-app “INSET_APPNAME_HERE”. This will provide you with the basic framework you need to get started on building your portfolio. From there npm install &amp;&amp; npm start or yarn install &amp;&amp; yarn start. Now your app is alive on a local server and ready to be opened in your preferred text editor.</p><p><em>This should produce an app template that looks similar to this…</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/297/1*AyNHSl0odrq-pRJjX5UfRg.png" /></figure><h3>If you already have a React app.</h3><p>Run the command line npm install react-router-dom or yarn add react-router-dom inside your react app. This installs the package that allows you to import router features into your app.</p><p>The next few steps, I am going to provide one general framework for laying out your react routes. However, as Dan Abramov <a href="https://twitter.com/dan_abramov/status/1027245759232651270?lang=en">concisely puts</a>, the file structure is entirely up to you. If this doesn’t feel right for you or your project, do it differently.</p><h3>Step 1: BrowserRouter, Route and NavLink.</h3><pre>import React, {Component, Fragment} from ‘react’<br>import {BrowserRouter as Router, Route, NavLink} from ‘react-router-dom’</pre><p>Next, you’ll want to add the above imports to the top of the parent component or container holding your most abstracted and widely-used states, functions, ect.</p><p>If you’re in the habit and/or mood to understand what the code you’re tossing into your app does, here’s a great (and succinct) <a href="https://stackoverflow.com/questions/45450289/whats-the-difference-between-the-react-router-v4-router-types">explanation</a>:</p><blockquote><strong>BrowserRouter</strong> is a React Component that watches the URL and more or less passes the current path down to its children, while a <strong>Route</strong> will render some other component based on the URL information passed to it by its parent, <strong>BrowserRouter</strong>.</blockquote><p><strong>NavLink</strong>— is identical to the native react router Link component, except it permits further styling functionality.<br><strong>BrowserRouter as Router</strong> — allows you to implicitly refer to BrowserRouter by referring to it as Router instead. Whether you do this or not, you’ll still be using BrowserRouter. The rename purpose is purely syntactical sugar.</p><p><em>Applied, you can expect your three components to look something like…</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/902/1*dknDF54zUZESkVGxpPuxyw.png" /><figcaption>Using Router, Route and NavLink to render the Home component</figcaption></figure><p><strong>&lt;Fragment/&gt; </strong>— it’s an inherited React Component that allows you to render multiple children without having to wrap each one, and the parent, in a &lt;div/&gt;.</p><h3>Step 2: Component, Render or Children.</h3><p>A react route has three rendering methods, or three different ways you can render a component or function to a page through a route. Each of these rendering methods accepts route props which you can read more on <a href="https://reacttraining.com/react-router/core/api/Route/route-props">here</a>.</p><p><strong>For now, here are the three rendering methods to get acquainted with:</strong></p><p>1. We use <a href="https://reacttraining.com/react-router/core/api/Route/render-func"><strong>&lt;Route render/&gt;</strong></a> when we want to harness the power of an anonymous function to pass down props — whether those are props from the state or properties from the route itself (For example: using the “URL” to build more links or the “path” to build more routes).</p><p>2. We use <a href="https://reacttraining.com/react-router/core/api/Route/component"><strong>&lt;Route component/&gt;</strong></a> when we want to render a component (brilliant, I know) or predeclared function. Every time a route with a component render method gets clicked, it rerenders (or mounts and unmounts) the component/function. So, depending on your performance and/or site objectives, keep this in mind while developing your portfolio.</p><p>3. We use <a href="https://reacttraining.com/react-router/core/api/Route/children-func"><strong>&lt;Route children/&gt;</strong></a> when we want to render a component or function regardless if the route matches — typically used for strategic UI decisions. The children render method receives all the same route props that render and component do except when a component doesn’t match the route; its match URL value is then match: null.</p><p><em>Although we will only we using the first two in this article, the children rendering method can be helpful if you’re wanting to simultaneously render components disconnected to the route path or URL.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/999/1*k6FBQWLb5ePZ-pFnRYyugw.png" /><figcaption><em>Using the render and component route rendering methods</em></figcaption></figure><h3>Step 3: Exact, Match and Nested Routes.</h3><p><strong>Exact</strong> is a boolean property of <strong>&lt;Route/&gt;</strong> that allows to specify if the component gets rendered every time the route <strong>includes</strong> a match versus every time the route is matched <strong>exactly</strong>. <em>The difference looking something like…</em></p><pre>&lt;Route path=&#39;/blogs&#39; component={ Blog } /&gt;<br>&lt;Route path=&#39;/blogs/thebestblog&#39; component={ BlogPost } /&gt;<br>&lt;Route path=&#39;/blogs/thebesterblog&#39; component={ BlogPost }/&gt;</pre><p>Each time blogs <em>best</em> and <em>bester </em>would render, so would the Blog Component. If we include exact, comme ça…</p><p>&lt;Route exact path=’/blogs’ component={ Blog } /&gt;</p><p>… the world becomes a better place to be, with unwanted parent components evaded upon BlogPost read.</p><p>Alright. So, <strong>Nested Routes.</strong></p><p>They sound intimating — and to be fair, are fairly displeasing the first few impressions. At the end of a tediously long, bonding day together (and when you need to render a child of component), they are surprisingly manageable and supportive in meeting our highly-specific goals.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/890/1*crxWUHLR9iiaTryfr9jaAA.png" /></figure><p><em>In the first route above</em>: we are creating a<strong>Nested Route</strong> in order to pass our projects down to our Portfolio Component, so we can display our Pink Floyd-inspired work for all.</p><p><em>In the second route above</em>: we are creating a <strong>Nested Route</strong> to pass our projects and the router props (match, location and history) down to our Project Component. This allows us to iterate through each of our projects, which you’ll see below.</p><p><strong>match </strong>is one of three route props (the other two being <strong>history</strong> and<strong> </strong><strong>location</strong>). <strong>match</strong> allows you to obtain information about <em>how</em> a &lt;Route path&gt; matched the URL, including properties like:</p><ul><li><strong>params </strong><em>object</em>— key/value pair(s) parsed from the dynamic segment of the URL; for example, the :id in this &lt;Route path=”/giraffes/:id” /&gt; produces a param object.</li><li><strong>isExact</strong> (<em>boolean</em>— was the entire URL matched exactly?)</li><li><strong>path</strong> (<em>string</em>— provides the entire path of the URL; helps when building Routes)</li><li><strong>URL</strong> (<em>string</em>— provides the matched portion of the URL; helps when building NavLinks)</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/863/1*LSLFFWeEtiOqy3Ifs-qUcA.png" /><figcaption>Using match and its params object to define to grab the :id or dynamic segment from the URL</figcaption></figure><p>Here we are taking our projects prop and our match router prop, destructuring them into variables, grabbing the id param from match param object and displaying them in HTML’s most profoundly revolutionary element, &lt;h1/&gt;.</p><p><strong><em>Grab a template </em></strong><a href="https://github.com/vio1337/routes-template"><strong><em>here</em></strong></a><strong><em> to get started.</em></strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3105d54f0525" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[JavaScript Promises.]]></title>
            <link>https://medium.com/@violetmoon/javascript-promises-f4c5625aea1a?source=rss-34dd0115b2a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/f4c5625aea1a</guid>
            <category><![CDATA[promises]]></category>
            <category><![CDATA[callback]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[asynchronous]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Violet Moon]]></dc:creator>
            <pubDate>Thu, 18 Oct 2018 02:41:52 GMT</pubDate>
            <atom:updated>2018-10-18T14:27:51.018Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yUzdM0s16XMy37FpeuGRNw.jpeg" /></figure><p>JavaScript promise objects are made up of two parts: the eventual completion (or failure) of an asynchronous function and the output returned from that operation.</p><p>The promise itself is a stand-in value until the operation has been completed. Once finished, the promise returns a status update of the operation: <em>fulfilled</em> (the operation ran successfully) or <em>rejected</em> (the operation failed). If the status is <em>pending</em>, your operation has not finished running.</p><p>Next, the promise object returns a promise to supply the resolve or reject value to the next promise object. Thus, initiating a progression that looks something like.</p><p><strong><em>Object</em></strong><em> creates </em><strong><em>promise</em></strong><em> that holds </em><strong><em>value</em></strong><em> to give to </em><strong><em>object</em></strong></p><p><em>that creates </em><strong><em>promise</em></strong><em> that holds </em><strong><em>value</em></strong><em> to give to </em><strong><em>object</em></strong></p><p><em>that creates </em><strong><em>promise</em></strong><em> that holds </em><strong><em>value</em></strong><em> to give to </em><strong><em>object</em></strong></p><p><em>that creates </em><strong><em>promise</em></strong><em> that holds </em><strong><em>value</em></strong><em> to give to </em><strong><em>object</em></strong></p><p><strong><em>and so on…</em></strong></p><p>You continue to step down in the promise chain the number of times you need to manipulate the return value of the previous promise object.</p><p>To understand promise objects, some prerequisite understanding is required…</p><h3><strong>Define: Asynchronous function</strong></h3><p>Unlike programming languages that separate main program execution and independent events (<em>Java, Go, Rust</em>), Javascript unifies these operations into a single process or flow — allowing for all code to executed in a sequence as opposed to in parallel.</p><p><em>Meaning, asynchronous functions enable specific code blocks to run out of sequence before the entire program has been executed.</em></p><p><a href="https://stackoverflow.com/questions/10570246/what-is-non-blocking-or-asynchronous-i-o-in-node-js">Here</a> is a great example you can play with.</p><p>As an event-driven programming language, JavaScript will not wait for the return value of a specific function before moving on to execute further code in the program. However, if we want to ensure that our program maintains its structured sequencing while using asynchronous functions, let’s take a look at…</p><h3><strong>Define: Callback</strong></h3><p>Because functions exist as objects in JavaScript, callbacks get the green-light. A function can now accept another function as its argument. This is badass and relevant because…</p><p><em>Callbacks ensure your functions run in order before running the rest of your program.</em></p><p>Once an async function has been executed, it produces a result (returning either data or an error). This result then gets pointed to a callback function that runs once the result is produced.</p><p>For example, the function below accepts a function argument, defines two variables — <em>name </em>and<em> feeling</em>, and sets those variables equal to the argument function’s parameters.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/779/1*G5jhxYQB3ttOQfNRmC8OeQ.png" /></figure><p>This is the output of running <em>user(greeting) </em>and filling out the two prompts…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*bP93C8rHq-4KVQ9peOJYZw.png" /></figure><p>For more info, <a href="https://medium.com/u/e9031892baf5">Brandon</a> wrote a great <a href="https://codeburst.io/javascript-what-the-heck-is-a-callback-aba4da2deced">article</a> on callbacks.</p><h3><strong>The Problem: Callback Hell</strong></h3><p>Callback hell occurs when — the deeper into callback darkness you travel, the faster your understanding of programming (and life) delicately, generously and unapologetically unravels.</p><p>Functions in functions… in functions in functions… in functions….</p><p><em>Basically, callback hell can be understood as the ensuing mental chaos created by long nested a/synchronous functions.</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/1*p7s-25ay7FCVCef4sU9X1w.png" /><figcaption><em>Although this program runs synchronously, each function in the nested callback tree will not move on to the next function until the previous value has been returned — making it ideal for performing asynchronous functions sequentially.</em></figcaption></figure><h3><strong>Welcome, JavaScript Promises.</strong></h3><p>We’re back! Promises derive much (if not all) of their value from alleviating the mental, emotional, psychical and spiritual strain of callback hell.</p><p><em>Promises are returned objects you can chain callbacks onto the end of — instead of passing callbacks into each iteration of the function.</em></p><p>Next, whether you want to display the resolved or rejected value of the promise object will determine which helper method you will chain to your previous promise.</p><p><strong>Meet .then()</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/697/1*8LFcb9xZCRO4t57S9hkxnw.png" /></figure><p>If you want to display the resolution, or successfully completed return, of a promise object, you will want to chain on — <em>.then()</em></p><p><strong>Meet .catch()</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/721/1*91BIqCbtEKQ74Ha2_RtR3Q.png" /></figure><p>If you want to display the rejection, or error value, of a promise object, you will want to chain on — <em>.catch()</em></p><p>Now, if we want to “promisify” a callback hell sequence into more approachable, attractive, girl-next-door code, we could add the <em>.then() </em>chain to each function until we reach our final, desired return value.</p><p>Taking our nested function mess from the callback hell example above, here’s what a promise restructure could potentially look like…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/815/1*rbCXakIgWhOCw0lV42gYew.png" /></figure><p>Running the program above, the output sequentially looks something like…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*x9cMe5QWiWb8OXu_jJh8LA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/454/1*RHOCv4kDsC9ZDdtR_InCBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/456/1*PIqFRcac9ZW7H25uRrRZwA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/1*Lawq5TJf_FNpPwAWniYI0w.png" /></figure><p><strong><em>Bonus! </em></strong>Because each result from the previous function returns a single parameter, you can also call the promise functions like this…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/666/1*yWpR8s5mkMKBTjSrfYxr3Q.png" /></figure><h3><strong>Final Recap</strong></h3><p>Callbacks are a much-needed solution for coordinating and sequencing async functions within an event-driven programming language, like JavaScript.</p><p>Promises transform nested a/synchronous functions into little (or extensive) coding block blessings by simplifying how to write a series of callbacks.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f4c5625aea1a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ActiveRecord, Sinatra and ERB.]]></title>
            <link>https://medium.com/@violetmoon/activerecord-rest-and-sinatra-frankenstein-ing-the-internet-3004f656717f?source=rss-34dd0115b2a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/3004f656717f</guid>
            <category><![CDATA[activerecord]]></category>
            <category><![CDATA[restful-api]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[sinatra]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Violet Moon]]></dc:creator>
            <pubDate>Wed, 19 Sep 2018 21:45:29 GMT</pubDate>
            <atom:updated>2018-10-18T02:42:21.599Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*VYSaS5cCKDkMWyWGSZ4z7Q.jpeg" /></figure><p><strong>REST</strong>, or representational state transfer, is a reusable package of patterns, constraints, design decisions and vocabulary for developing web services.</p><p>In other words, REST “is an architectural style that defines a set of constraints to be used for creating web services “ — Thanks, <a href="https://en.wikipedia.org/wiki/Representational_state_transfer">Wikipedia</a>.</p><p>Most generically, a <strong>web service</strong> is the software functionality that allows one device to communicate with another device using the World Wide Web.</p><p><strong>HTTP</strong>, or hypertext transfer protocol, is a request-response protocol that improves or enables the communication between a client (examples: web browser, mobile apps, web crawlers) and a server.</p><p>An <strong>HTTP resource</strong> (example: HTML, CSS, JavaScript, image) is identified and located by the URI portion of a URL.</p><p>Say our website is: <a href="http://www.awesome.com/people/me"><strong>www.awesome.com/people/me</strong></a>. The URL can be defined as this entire address. The URI (uniform resource identifier) of this URL would be: <a href="#"><strong>/people/me</strong></a><strong>.</strong></p><p>A model-view-controller, or <strong>MVC</strong>, bundles each of these functionalities into a workable, socially-approved Frankenstein monster. Just as Dr. Frankenstein combined this guy’s eye with that women’s heart, the MVC architecture connects your database to your HTTP resource through a controller.</p><p><strong>Eye </strong>= view</p><p><strong>Heart </strong>= model</p><p><strong>Dr. Frankenstein </strong>= controller</p><p><strong>Dr. Frankenstein’s monster </strong>= my website</p><h3><strong>DATABASE</strong></h3><p>Ruby’s primary ORM is ActiveRecord (more details on that <a href="https://medium.com/@violetmoon/understanding-orm-frameworks-with-ruby-and-activerecord-83a9e9d8490e">here</a>) — ActiveRecord’s CRUD methods are used to access or manipulate information from a database. These methods include: <em>Create, Read, Update </em>and<em> Delete. </em>So if you have a class labeled “Monster” you could:</p><p><strong>Monster.create </strong><em>— create a new instance or row in your table</em></p><p><strong>Monster.all </strong><em>— display all instances or rows in your table</em></p><p><strong>Monster.update </strong><em>— update an instance or row attribute within your table</em></p><p><strong>Monster.destroy </strong><em>— delete an element of the entirety of your table</em></p><h3><strong>CONTROLLER</strong></h3><p>A controller defines the routes that connect a database to a user interface. In <a href="http://sinatrarb.com/intro.html">Sinatra</a>, this route is an HTTP method paired with a URL-matching pattern — in this case, pairing HTTP verbs to an URI. The simplified formula looks like, <strong>HTTP verb + URI = RESTful route</strong>. Continuing with the example above:</p><p><strong>GET<em> + “/monsters” </em></strong><em>— conventionally used to display Monster.all through ActiveRecord</em></p><p><strong>POST + <em>“/monsters/new” </em></strong><em>— used to initialize a row using ActiveRecord’s table_name.create</em></p><p><strong>PATCH <em>+ “/monsters/:id/edit“ </em></strong><em>— editing a row’s attribute’s using Monster.update</em></p><p><strong>DELETE <em>+ “/monsters/:id” </em></strong><em>— conventionally used to remove, or Monster.destroy, a row</em></p><p><strong>REST is the designated architectural style. RESTful routes are the implementation of that paradigm.</strong></p><h3><strong>VIEW</strong></h3><p>ERB, short for embedded Ruby, is a Ruby feature that enables you to combine plain HTML text with Ruby code to create a single, dynamic template for viewing. For wormhole readers, <a href="https://www.stuartellis.name/articles/erb/">this</a> article dives deeper into ERB history and functionality. As far as views go, once you assign your erb file to a specific RESTful route in the controller, it will display on your web browser/mobile app/etc.</p><p><strong><em>Pieced together: our model would be supported by ActiveRecord, our view would be presented using an ERB file and our controller would be enabled by Sinatra.</em></strong></p><p><strong>Example:</strong> <em>If we want a blog, how would we layout our RESTful routes?</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p9ld6YeR-hL0txhATmU4UQ.png" /><figcaption><em>*You can also use PUT to update every attribute of an object — or the entire row of a table. For modifying single attributes however, PATCH allows you to manipulate the object’s data without having to redefine every attribute assigned to that object.</em></figcaption></figure><blockquote><strong>1 . <em>GET</em> request displaying all of your posts.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/696/1*POsrAzYJADNoVuLV3uvwGw.png" /><figcaption>Row #1 in the table above, you’ll find each of these elements broken down into categories.</figcaption></figure><blockquote><strong>2 . <em>POST</em> request creating a new post.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/847/1*DllsgbMv3adLOAizL4l4-Q.png" /><figcaption>Row #2 in the table above, you’ll find each of these elements broken down into categories.</figcaption></figure><p><strong>Important Sinatra Interlude: </strong>In order to use a RESTful route other than POST and GET in Sinatra, you will have to add <em>Rack::MethodOverride</em> above all your controllers. Then in the form where you are wanting to update or delete information, you would need to add an additional input line that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*QNsvLOXpiLdZzcGvl9PF-A.png" /></figure><p>This line of code —inside of your form— will translate the POST request to whatever you set the value attribute to (PATCH, DELETE or PUT).</p><blockquote><strong>3 . PATCH request editing a post attribute.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/901/1*wpOKwKfoQq-BLCoWYR8L4g.png" /><figcaption>Row #3 in the table above, you’ll find each of these elements broken down into categories.</figcaption></figure><blockquote><strong>4 . DELETE request that deletes a post.</strong></blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/731/1*PGadOfdHAArQbJvaueE55g.png" /><figcaption>Row #4 in the table above, you’ll find each of these elements broken down into categories.</figcaption></figure><p><strong>Nuance tips —</strong></p><ul><li><strong><em>Make sure your redirects are in double quotes.</em></strong></li><li><strong><em>Begin your URI’s with a backslash.</em></strong></li><li><strong><em>Param attributes can be written as strings (params[“id”]) or symbols (params[:id]). Regardless, they will still be affiliated to their parent hash.</em></strong></li></ul><p>For <em>another</em> helpful <a href="https://medium.com/@thejasonfile/restful-routing-2056f799223e">RESTful routes visual</a>, <a href="https://medium.com/u/4c949e4f0837">Jason Arnold</a> created a great one.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3004f656717f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ORM, Ruby and ActiveRecord.]]></title>
            <link>https://medium.com/@violetmoon/understanding-orm-frameworks-with-ruby-and-activerecord-83a9e9d8490e?source=rss-34dd0115b2a2------2</link>
            <guid isPermaLink="false">https://medium.com/p/83a9e9d8490e</guid>
            <category><![CDATA[learn-to-code]]></category>
            <category><![CDATA[orm]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Violet Moon]]></dc:creator>
            <pubDate>Mon, 10 Sep 2018 15:10:56 GMT</pubDate>
            <atom:updated>2018-10-18T02:43:00.703Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*43TU7StyO3uZP2UFBPkRFQ.gif" /></figure><p>Right off the bat, what is ORM? Literally, it means object relational mapping — but if you are like me, that meant absolutely nothing. It sounded nice though.</p><p><em>Object. Relational. Mapping.</em></p><p>Incalculable deep dives later, I decided to break through the ambiguity to break down the concepts, integrations and functionality of ORM frameworks. Going forward, navigating databases no longer has to be exhausting or anxiety-provoking.</p><p>If you’re coding in an object-oriented programming language, harnessing the power of ORM simplifies and organizes the implementation of a relational database within your OO-language of choice.</p><h3><strong>Concepts: What does an ORM framework do?</strong></h3><p>ORM is the middle wo/man between a relational database management system and your preferred object-oriented programming language. She eases communication between both parties so that the conversation is more fluid, graceful and intuitive. This support is called mapping.</p><p>Mapping, or sometimes referred to as wrapping, draws connecting vectors between the database and your language’s models — or “wraps” your queries in more direct, personable code.</p><p>While developing programs, ORM provides conventional methods for integrating a database into your code. It allows you to access a database table like a Ruby class and a row of your table like an instance of your class, as illustrated below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/952/1*3kOB8sMaJcJXFwlWNQYIRQ.png" /></figure><h3><strong>Integrations: Who can use an ORM?</strong></h3><p>There are different types of ORM frameworks depending on the object oriented language you’re using. Languages conventionally accepted as functional can also have designated ORM systems to support a language’s more object-oriented functionality.</p><p>Although an ORM framework is more frequently created to simplify the interaction between a relational database and an object-oriented language, languages like JavaScript encapsulate this aforementioned exception.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/953/1*1g7HWYsk_yaByAGD3mYkqA.png" /><figcaption><em>*</em>Despite traditionally deferred to as a functional programming language, JavaScript encapsulates object-oriented functionality that enables it to require a database — and thus, benefit from an ORM framework.</figcaption></figure><h3><strong>Functionality: How do an ORM framework and an OO-language interact?</strong></h3><p>Using Ruby as my object-oriented programming language and SQL (Structured Query Language) as my relational database, the following examples will flow through adding class instance’s to a table with the purpose of visually comparing the greater simplicity of each process.</p><p>The table below illustrates what we’d like our code to produce: a list of giraffe friends with corresponding characteristics.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/948/1*INHK7vJX2UNZ4L09SkgG_w.png" /><figcaption><em>*In this example, I’m using the 0 for false and 1 for true to mirror a boolean datatype.</em></figcaption></figure><p><strong>Basic Addition.</strong></p><p>Imagining we have just created a new giraffes table, the lines below illustrate how we would use the SQL function INSERT INTO to hardcode our giraffe friends into our table one by one. It gets the job done but if we had anymore friends (giraffes are nice, so it’s possible), our program would quickly resemble the DMV — inefficient and slow.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/829/1*gMyOuemSecMQZER5kbKjSg.png" /></figure><p><strong>Simplifying with Methods.</strong></p><p>There’s a lot more code here. How could it be simpler? Well, as we continue to make more giraffe friends we want to be able to add them to our table with more ease now and less code later. By creating a model with several class methods we can 1) collect all of our giraffes in one array using <em>self.all</em> and 2) add them to our table using <em>self.save</em> — all without having to write INSERT INTO forty seven hundred times. Arbitrary number. Real talk.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/878/1*f-wPweVLd3C4hACb9kAzcQ.png" /></figure><p><strong>ORM Implementation.</strong></p><p>ActiveRecord is the most-adopted ORM framework by Rubyists — You can install it <a href="https://rubygems.org/gems/activerecord/versions/5.0.0.1">here</a>.</p><p>At its core, ActiveRecord is a library that, through extensive and detailed development, enables you to call SQL functions more intuitively and precisely. As Ruby on Rails built-in ORM, ActiveRecord at its most basic level allows you to interact with data using CRUD methods — create, read, update and destroy. By inheriting these ActiveRecord base methods, your class instantly has access to basic CRUD functions that can clean up your code.</p><p>For example, when building out our giraffes table, the difference between typing out SQL CRUD queries in the example above and using ActiveRecord is that, ActiveRecord’s base methods turn 6–10 words into one.</p><p>Simply, you are inheriting pre-defined functionality, like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/680/1*ypFTOFoSVoHs39UP7nHscg.png" /></figure><p>Now if you wanted to add a new giraffe friend to the table, you would use ActiveRecord’s built-in create function to insert a new row to the table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/877/1*hsaCZD0cj2sgAmvcs-YMjQ.png" /></figure><p>So instead of having to create new class methods in our Ruby program every time we wanted to manipulate or call our data, we can inherit those features from ActiveRecord and simply create, read, update or destroy.</p><h3><strong>Attitudes: What are the benefits and drawbacks of using an ORM?</strong></h3><p>There are hundreds of discussions debating the value of ORMs over raw database queries, like SQL. The bell-curve consensus encapsulates a hybrid approach emphasizing: the benefits of ORM frameworks for simple, tedious CRUD functionalities and raw SQL’s for complex join tables and larger projects that benefit from more explicit (and therefore speedier) directions.</p><p>In this Hacker News <a href="https://news.ycombinator.com/item?id=16809620">discussion</a>, I found several great one-liners exemplifying mainstream moods towards object relational mapping frameworks.</p><p>Your pro-ORM advocates generally propose something like,</p><p><em>“Life is too short to maintain every single query.”</em></p><p>While your SQL or raw database query proponents argue,</p><p><em>“ORMs add a layer of complexity to your code and a huge risk of really bad SQL.”</em></p><p>Often ORM can serve as a crutch that alienates true understanding of a database and how it works. However, if your foundational knowledge of SQL (or your preferred relational database) is sound and comprehensive, harnessing an ORM’s capacity to support your program can be a truly powerful exhale.</p><h3><strong>Further reading and resources.</strong></h3><ul><li>If you’re curious about SQL, check <a href="https://www.infoworld.com/article/3219795/sql/what-is-sql-structured-query-language-explained.html">this</a> out.</li><li>To read more on Ruby’s ORM system, <a href="https://guides.rubyonrails.org/active_record_basics.html">this</a> covers ActiveRecord.</li><li>For personable ORM discussions, scroll through <a href="https://stackoverflow.com/questions/1279613/what-is-an-orm-and-where-can-i-learn-more-about-it">this</a>.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=83a9e9d8490e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>