<?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 Jennifer Ingram on Medium]]></title>
        <description><![CDATA[Stories by Jennifer Ingram on Medium]]></description>
        <link>https://medium.com/@jennyjean8675309?source=rss-760302d1b208------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*u1MBert01upI6um1dzW7Kg.jpeg</url>
            <title>Stories by Jennifer Ingram on Medium</title>
            <link>https://medium.com/@jennyjean8675309?source=rss-760302d1b208------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 11:49:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jennyjean8675309/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[Integrating ActionCable with React]]></title>
            <link>https://javascript.plainenglish.io/integrating-actioncable-with-react-9f946b61556e?source=rss-760302d1b208------2</link>
            <guid isPermaLink="false">https://medium.com/p/9f946b61556e</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[tech]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Jennifer Ingram]]></dc:creator>
            <pubDate>Mon, 06 Jan 2020 21:02:47 GMT</pubDate>
            <atom:updated>2020-01-08T00:08:34.004Z</atom:updated>
            <content:encoded><![CDATA[<h4>Action Cable is a framework provided by Ruby on Rails that allows developers to utilize WebSockets in their applications.</h4><p>WebSockets have been around since 2008 and are a completely separate protocol from HyperText Transfer Protocol (or HTTP). I’m fairly familiar with the communication between a client and server using HTTP — the client (my browser) opens a connection and sends some sort of request to a server (maybe it’s to load a website, or handle input from a form), the server handles that request, and responds with some sort of information, and the connection is closed. This back and forth works pretty well for most situations. There are times however, when an application needs updated information from the server pretty frequently. One example is a chat feature.</p><p>If I belong to a chat room, the only way that my computer (the client) knows whether my friends have sent me any messages (if I’m using HTTP) is to make frequent, periodic calls to my server to check for any updates. This is known as <em>polling,</em> and, as I’m sure you can guess, is pretty inefficient. WebSockets eliminate this inefficiency by creating a TCP connection between client and server that <em>stays open</em>. Then, rather than the client requesting updates from the server over and over again, the server, as soon as it receives any updates, <em>automatically pushes them out</em> to all of the clients on that connection. It’s like upgrading from walkie-talkies to a cell phone.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FkkFOYzdDi8Jaw%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FkkFOYzdDi8Jaw%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FkkFOYzdDi8Jaw%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/00160dcf84454a7acbf0ae990be10820/href">https://medium.com/media/00160dcf84454a7acbf0ae990be10820/href</a></iframe><h3>Action Cable &amp; React</h3><p>The documentation for Action Cable, like most Rails documentation, is pretty thorough. It does however, assume that you are using Rails as a full-stack framework. If you plan on combining a Rails backend with a separate frontend framework, the resources for how to incorporate ActionCable are scarce. This blog is my attempt at clearing up some of the confusion and to help others get started. I’ve created a simple chat room application and will walk you through how I’ve set mine up. If you would like to see the code in full, here are links to my repos on Github…</p><p>Backend — <a href="https://github.com/jennyjean8675309/chitter_chat">https://github.com/jennyjean8675309/chitter_chat</a></p><p>Frontend — <a href="https://github.com/jennyjean8675309/chitter_chat_frontend">https://github.com/jennyjean8675309/chitter_chat_frontend</a></p><h4>Getting Started</h4><p>My Rails backend is fairly simple — I wanted to design my application to have three chat rooms. Each chat room would have many messages (from many users), and messages act as a join table between rooms and users. So my backend only has three models — room, message, and user, with corresponding controllers.</p><p><em>*My application also incorporates ActiveStorage for user image uploads, and authorization (using the bcrypt gem and jwt tokens), which has resulted in some extra controllers, but these are not necessary to understand Action Cable —I’ll try to only refer to the code that is relevant to Action Cable in this post.</em></p><h4>Routes</h4><p>My first step was to set up my routes for the backend. In your routes.rb file, you’ll need to specify the following:</p><pre>resources :rooms, only: [:index, :show]<br>resources :messages, only: [:index, :create]<br>resources :users, only: [:index, :create]<br>mount ActionCable.server =&gt; &#39;/cable&#39;</pre><p>The first three lines should be fairly familiar if you’ve used Rails before. The last one is a little strange — let’s talk about it for a moment. Remember that WebSockets are their own protocol — they don’t need to specify the type of request (i.e. get, post, put, etc.) like we do with HTTP. Instead, we simply <em>mount </em>a route for our server to handle the WebSocket connections— our frontend will connect to the ‘/cable’ endpoint to instantiate a connection — but we’ll get to that a bit later.</p><h4>Connections</h4><p>Connections, as I’m sure you can probably guess, connect the client to the server. A connection is initialized whenever a WebSocket (from the client) is accepted by the server. In order for a WebSocket to be accepted, Rails provides a parent ApplicationCable::Connection class (found in channels -&gt; application_cable -&gt; connection.rb) whose sole job is to authenticate and authorize the current user. Because my frontend is handling authentication for my application, I am ignoring this process on my backend and leaving the class empty.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/535/1*Cy9Weau0C5DXuPkHSfvfnA.png" /></figure><p>A single Action Cable server can handle multiple connections, and a single user (i.e. client) can open multiple connections simply by opening a new browser tab or window. In Action Cable speak, clients who are connected to your server through a WebSocket are called <em>consumers</em>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FrqQDt5VKYKA%3Ffeature%3Doembed&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DrqQDt5VKYKA&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FrqQDt5VKYKA%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/7d5d43229142535948d86a6cdcbe1ef2/href">https://medium.com/media/7d5d43229142535948d86a6cdcbe1ef2/href</a></iframe><p>To demonstrate what I mean, in the video demo above I have a single client (my Chrome browser) instantiating two separate WebSocket connections to my backend Action Cable server, by having two windows open. They are both connected to my server, but on the right side I am logged in as ‘betty’, and on the left side as ‘harold’. Because both users have subscribed to the Cat Lovers Room (a single channel), there is a constant stream of communication flowing back and forth. This means that when Betty sends her message, Harold receives it automagically. This is what is known as a Pub/Sub link (or Publish-Subscribe). The <em>publishers</em> (i.e. senders) of information push out the data to <em>all subscribers</em> of that particular channel (without directly identifying individual recipients). This means that if there were a bunch of other users subscribed to the Cat Lovers Room they would all receive Betty’s message at the same time.</p><h4>Channels</h4><p>You can think of a channel as a single communication stream, in which information flows both back and forth. I have three chat rooms, and each chat room has its own channel — each user that wants to chat about cats can subscribe to the Cat Lovers Channel, and can send information to all other users subscribed to that channel, as well as receive information from all other users subscribed to that channel. The same is true for my Trekkies Channel and Conspiracy Theorists Channel.</p><p>Similar to ApplicationRecord and ApplicationController, Rails creates a parent ApplicationCable::Channel that handles all shared logic between your channels.</p><p>Just as controllers in Rails correspond to models, so too, do channels. Because all three of my channels are instances of the Room model, I only need to make one Channel class, which I’ve named RoomsChannel. How then, might you ask, will my application know <em>which room</em> a user is subscribed to? The answer is that my frontend will send information about the room to the backend (in the form of params), my RoomsChannel class will then find the particular room specified, and stream information only for that room.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4E2C6rlQ_7zo-6OwR5M-aw.png" /></figure><p>Notice that my RoomsChannel inherits from ApplicationCable::Channel. Now let’s move to the frontend (client side) to see how this is all related.</p><h4>The Frontend as Consumer</h4><p>I’ve created a basic React application for my frontend. In order to utilize WebSockets, the first thing that I need to do is set up my frontend client as a <em>consumer</em>. Remember that a single user (i.e. a physical person) can have multiple connections open at once, and therefore can have multiple consumers (think of consumers as browser tabs or windows).</p><p>First, run</p><pre>npm install actioncable --save</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R4Nfr1PMkwTPfn6dmMT64Q.png" /></figure><p>Installing the actioncable node package allows us to use the createConsumer() function. Remember when we mounted the route for WebSockets on our backend? — this is where we open that connection. Notice that the prefix for the url is <em>not</em> http , but is ws instead — this is because we’re now in the world of WebSocket protocol!</p><p>Once we’ve created our frontend client as consumer, notice that I’m now passing the CableApp object down as props to my App Component.</p><h4>Data Structure</h4><p>I have a lot of stuff happening in App, but we’re going to ignore the bulk of it, for now. First, I’d like to focus your attention on state for the App Component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/888/1*32YOuNMZrUbe16CxRDfFGQ.png" /></figure><p>The important part to note here is the <em>data structure</em> for currentRoom — I’ll adhere to this same data structure throughout the application. It’s important to realize that this data structure also matches the broadcast information from the backend. Referring back to rooms_channel.rb …</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KtLTXBq_PASqq2pKxTOrvg.png" /></figure><h4>Sending Information</h4><p>Now things get a little tricky, but I’ll try to be as clear as possible… stick with me now!</p><p>The main component that I want to focus on is my RoomShow component. I have a route declared for this component in App.js.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WUxgnosEpwmg01SpaTrwZQ.png" /></figure><p>This is what my RoomShow component looks like in the browser…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WNoLx1mW4y8SKXkjIx9THg.png" /></figure><p>Notice that my RoomShow component holds the form for a user to submit a new message. It is also the parent component of my ChatFeed component (the gray box), which is the parent of individual ChatMessage components. RoomShow is also the parent of one other component that is invisible to us — RoomWebSocket — more on that in a bit.</p><p>Notice what I’m sending down as props from App…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*TZXrFWl0Z9YLhB9HabicQw.png" /></figure><p>The first is router props, the second, cableApp, we’ve already seen, and is the connection to the WebSocket we created from index.js. The next two, getRoomData and updateApp are functions…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9oCXNJNcCFkijhtrY3EWJA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/942/1*QXBszJC9mhTjIsFBs7XthQ.png" /></figure><p>Both roomData and currentUser are pieces of state that keep track of the current room my user is viewing, and the current user that is logged in, respectively.</p><p>Now back to that invisible RoomWebSocket component that I mentioned above…</p><h4>WebSocket Component</h4><p>The last component rendered from our RoomShow component is RoomWebSocket. Though this component is invisible (i.e. it’s not rendering anything in the browser) it is critically important. It receives three props from RoomShow…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*Atdz_I57Vyg4QdfoIFD97w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/613/1*o-dOsogf8_hvXqtBE_zrYg.png" /></figure><p>All of the action happens when this component mounts. The first function that gets invoked is getRoomData(). This is the only place in my application in which I call this function. It passes in as an argument the room id (which I grab from my window location), makes a fetch call to my backend, and sets state for the current room my user is viewing.</p><h4>Creating a Subscription</h4><p>Our RoomWebSocket component is also the place where (surprise! surprise!) the communication between our client and server (through the connection we opened in index.js) happens.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/695/1*5Rm87QSXwBpkk2VmvFCKAw.png" /></figure><p>Notice lines 8–11 above — here, our consumer is becoming a subscriber by creating a subscription. There are two arguments (objects) passed to the subscriptions.create() function. The first object has two keys — channel (required), which specifies the channel that we are creating a subscription for (‘RoomsChannel’), and room, whose value is the room id that we grab from the window location.</p><p>If I place a byebug in the subscribed action of my RoomsChannel, like so…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*fAmrB99vPGi0yDAEa_Sb6A.png" /></figure><p>…I can pause in my code for a moment to expect params from the terminal when I navigate to a RoomShow page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K9ctsqJz-mK_h491ojucNg.png" /></figure><p>Notice that our subscribed action from RoomsChannel first finds the specific room whose channel we want to connect to, then uses the stream_for command to create a communications stream. After removing the byebug, you should be able to see a message in your terminal that you are in fact live-streaming information!!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Q5lvsehSy4Wk3_t_eEnY3A.png" /></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl6Td5sKDNmDGU%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Fl6Td5sKDNmDGU%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Fl6Td5sKDNmDGU%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/2c94b06f3d65ef766b4e4b909e02f964/href">https://medium.com/media/2c94b06f3d65ef766b4e4b909e02f964/href</a></iframe><p>Don’t get too cocky now…</p><h4>Broadcasting</h4><p>Now we know that we are indeed streaming information from our frontend consumer to the backend, but how do those updates get pushed out? The answer comes from the way we handle our messages.</p><p>When a user submits a new message, an HTTP post request is made to the backend, and is handled by the MessagesController…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/805/1*dW4XiGxoQB8ZSEhClieh5w.png" /></figure><p>In the create action of my MessagesController, if a new message is successfully created and saved to my database, I then send out a new broadcast to the specific room channel that that message was created for.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/465/1*bRiqqN4myDKM-9jBzH4i4A.png" /></figure><p>The second argument to my subscriptions.create() function is an object with one key, received, that points to a callback function. When new information is received on that channel, as in the example above where I create a new message, this callback function is invoked and updates state in my application automagically!</p><h4>Conclusion</h4><p>In conclusion, WebSockets and Action Cable are pretty sweet! I hope that this introduction to Action Cable and React helps somebody out!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Ffxer59iENthBgPbkuA%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2Ffxer59iENthBgPbkuA%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2Ffxer59iENthBgPbkuA%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="415" frameborder="0" scrolling="no"><a href="https://medium.com/media/f93242f307a5f81ce57080665cbdbd86/href">https://medium.com/media/f93242f307a5f81ce57080665cbdbd86/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9f946b61556e" width="1" height="1" alt=""><hr><p><a href="https://javascript.plainenglish.io/integrating-actioncable-with-react-9f946b61556e">Integrating ActionCable with React</a> was originally published in <a href="https://javascript.plainenglish.io/">JavaScript in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connect Your React Application to a Rails API Using Active Storage (part 2)]]></title>
            <link>https://medium.com/@jennyjean8675309/connect-your-react-application-to-a-rails-api-using-active-storage-part-2-84e7978ba11d?source=rss-760302d1b208------2</link>
            <guid isPermaLink="false">https://medium.com/p/84e7978ba11d</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[rails-api]]></category>
            <category><![CDATA[active-storage]]></category>
            <dc:creator><![CDATA[Jennifer Ingram]]></dc:creator>
            <pubDate>Fri, 06 Sep 2019 20:15:05 GMT</pubDate>
            <atom:updated>2019-09-06T20:15:05.049Z</atom:updated>
            <content:encoded><![CDATA[<p>In my last post we started to build out a simple React application that used a Rails API with Active Storage on the backend to store user information (including an image file for their avatar). We created a user in our seed file, attached an image file to that user (in the form of a <a href="https://api.rubyonrails.org/classes/ActiveStorage/Blob.html"><em>blob</em></a>), and we were able to successfully fetch that user’s information from the backend and display their avatar on the frontend.</p><p>In this post (part 2), we’ll continue to build out our application, giving a user the ability to create an account from our frontend — including the ability to upload an avatar image from their computer — and we’ll store that information on the backend. If you missed part 1 of this post you can find it <a href="https://medium.com/@jennyjean8675309/connect-your-react-application-to-a-rails-api-using-active-storage-part-1-e59dcacc481b">here</a>.</p><h3>Letting the User Logout</h3><p>Before we move on to uploading an image, let’s give our users the ability to logout. To do that, I’m first going to refactor my NavBar Component. If a user is already logged in, they shouldn’t see the options to login or create an account on the NavBar — they should see a logout option instead.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pjP87z71t-SaKydytoBqxw.png" /></figure><p>Notice that now our NavBar is expecting some props. Let’s be sure to pass those down from our App Component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qgYCaiH1k6JsqiSqDIWvTw.png" /></figure><p>Now we’re passing down state for our CurrentUser, and passing down a logout() function that will reset state to be null when a user logs out. Let’s also change our conditional for the profile route to <em>redirect</em> a user to the login page if they’re not already logged in, rather than re-rendering the Login Component. In order to do this we need to add the Redirect Component to the list of things that we’re importing from ‘react-router-dom’ at the top of our file.</p><pre>import { Route, Switch, Redirect } from &#39;react-router-dom&#39;;</pre><p>This makes our code a little cleaner, and little less breakable.</p><h3>Sending Images to the Backend</h3><p>Let’s move on now to our CreateAccount Component and build out that form.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W3jRmGNFjUNP-5XI1vHyPw.png" /></figure><p>This form should look very familiar — it’s almost the same as our login form, but with some minor (but very important) differences. First, notice that now we have an additional input field that has a type of ‘file’. This simple little change is what gives you a button, ‘Choose File’, in your form. When a user clicks on that button, a window automatically pops up (similar to a Finder window) and allows the user to choose a file stored on their computer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nu4Ncu3wDVlFpLkKHbqSPg.png" /></figure><p>All three input fields are using the handleOnChange() function that is setting state based on the value of each input field. Notice however, that when we fill out that form, state for the avatar is a weird ‘fakepath’ string. This isn’t what we need — what we really need is the file itself.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/534/1*u03k2GMfzDpNrrwhwsri5w.png" /></figure><p>Let’s go back to our handleOnChange() function and do a bit of refactoring…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/964/1*ntUaK4-kjpaDvflVNZymew.png" /></figure><p>Because what we want from our file input is not the value (which is a simple string), but the <em>file itself</em>, we can refactor our function to first check if our input field has a name of ‘avatar’ — if it does, then we want the file that our user uploaded. We can grab that file using</p><pre>event.target.files[0]</pre><p>If the input field has a name of ‘name’ or ‘password’, then we will grab the values from those fields like before.</p><p>If we’ve grabbed our file correctly, then we should see it reflected in state…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qWThCpV57XcmZ5l0OwaM-A.png" /></figure><p>Cool. Now this.state.avatar is a file object with a name, size, and type!</p><p>Let’s also give our form an onSubmit event listener…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fjmQXmeFtue4zVZGt55Geg.png" /></figure><p>In order to save our user’s information to the backend, we’ll separate this into a couple of steps. First, we’ll make a post fetch to ‘/users’ to create a new user, and then we’ll write a separate method to handle the image upload.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/992/1*TQ1qJ6tGYJQ8MMBKVsIPrg.png" /></figure><p>As of now, we’re just logging our information to the console — we’ll address what we’re going to do with the data we get back from our fetch call in a moment. Let’s turn to our backend first and fill out our create action in our users controller…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JFob9nf1__au3Jr7HQDckQ.png" /></figure><p>Now, when we create a new user we see his information logged to the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pf-xzkZqkTkxIzAIR4jM9Q.png" /></figure><p>Once our User instance has been successfully saved on the backend, we can now write out the logic to upload his avatar. We’ll do this by writing a function, uploadFile(), that will take in two arguments — the file we want to upload, and the user object that we want to attach it to. We’ll invoke this function as soon as we get our user information back from the server.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*9ac-VAnOcnxe_8q8Ern8iA.png" /></figure><p>Now this is where the magic of our activestorage library from node package manager comes in. At the top of our CreateAccount.js file we need to import a Component, DirectUpload, from this library…</p><pre>import { DirectUpload } from &#39;activestorage&#39;;</pre><p>Then we’ll create a new instance of that component in our uploadFile() function, passing it two arguments — the file we want to upload, and a url.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TQBrc_WsrmdZ_ATqRF6ljw.png" /></figure><p>If we check out our routes on the backend, we can see that this url is indeed a valid path — it was provided for us when we installed Active Storage in our Rails application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zEk7455VVfST1aenCpN8Gg.png" /></figure><p>Even though this route does exist, we need to <em>explicitly</em> add it to our routes in our config folder on the backend. *Remember to kill your backend server and then start it up again to pick up those changes.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PgIW6FXMvuSbLU6Z9fz5PA.png" /></figure><p>Now let’s attempt to create that upload. The create method provided by Active Storage takes in a callback function. That callback function takes in two arguments — an error, and a blob. If our create method is unsuccessful, let’s log the error, else, let’s log that there is no error.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6HJ_LtZ5r_nugMNKHzpatw.png" /></figure><p>Notice too, that this route goes to a create action, inside of a direct_uploads controller, that comes from Active Storage. A quick glance at your controllers on your backend will reveal that this controller does not exist (at least not anywhere that we can find it). Let’s build it out!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AkI59QAEP5TSkrtx8dvGnQ.png" /></figure><p>Notice here that our new DirectUploadsController inherits from ActiveStorage::DirectUploadsController. Let’s fill out our form again to create a new account and see what happens…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*LN-H6Nm5bzz2H3ZAsp1jBw.png" /></figure><p>Ugh… we get this super ugly and mysterious error message — 422, Unprocessable Entity. We didn’t hit our byebug on the backend, but we can see that our create() function from the frontend did indeed console.log our error.</p><p>The problem here concerns Cross-Site Request Forgery. From the <a href="https://api.rubyonrails.org/classes/ActionController/RequestForgeryProtection.html">Ruby on Rails documentation</a>:</p><blockquote>Controller actions are protected from Cross-Site Request Forgery (CSRF) attacks by including a token in the rendered HTML for your application. This token is stored as a random string in the session, to which an attacker does not have access. When a request reaches your application, Rails verifies the received token with the token in the session. All requests are checked except GET requests as these should be idempotent. Keep in mind that all session-oriented requests are CSRF protected by default, including JavaScript and HTML requests.</blockquote><p>Well, that’s fine and dandy, but how do we get around it? Let’s place a skip_before_action helper method in our DirectUploadsController…</p><pre>skip_before_action :verify_authenticity_token</pre><p>*Disclaimer — I am fairly new to programming, and this was the only method I found to get activestorage to work with my ‘toy’ application. If you are building out a ‘real’ application (i.e. an application that <em>real</em> people will actually use on the <em>real</em> web) you don’t want to simply skip over any methods that are designed to prevent CSRF issues!</p><p>Now that we’ve added that line of code, when we submit our form we should be paused in our byebug from the create action in our terminal.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tOKqVeIv-2IrRvi1v5hAQw.png" /></figure><p>Looking closely at our parameters, we see that we have an object, a blob, with all of our image file’s information. We’ll use that to create a Blob instance (with a method provided by Active Storage).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MS-agRduK2a_y_1RqsGzBg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9k1xgc8qT55ZqOgNA6VRMA.png" /></figure><p>Resubmitting the form again, and checking the value of blob, we see that we do indeed have a Blob object with its own id, key, and all of the other stuff we need to keep track of. If we check out the database too, we see that we now have that blob instance stored on our active_storage_blobs table.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FCLt2odORRdowwTaY371Cw.png" /></figure><p>Cool! Now we need to send that newly created blob <em>back</em> to our frontend (in json format), where we’ll make <em>another</em> fetch call to the backend that will update our user, by attaching their avatar file to their user instance. Phew!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fcupuNhLAM4IE7-3-9nUCQ.png" /></figure><p>Using a private method, direct_upload_json, we parse our blob object into json format and then send that information back to the frontend. Notice that along with our object, we are also passing along a method, signed_id. We’ll use this method on our frontend in a moment. For now, I’ve placed a debugger in our uploadFile() function that will trigger if we don’t get an error back…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CjcabGibY0CSqK9xZ9o7bw.png" /></figure><p>And now we can check the value of blob…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bTGdODzD4_y3nTiTi37vDg.png" /></figure><p>Let’s update our user now with our new blob instance, created fresh from the server, by making another fetch request.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*E19d_bFzi8SXvrLHYy3wLQ.png" /></figure><p>Notice now that we’re using that method, signed_id. In order to attach a blob file to our user, Active Record needs a key to connect the two — that’s what signed_id does for us. In our backend, we need to fill out the update action in our users controller.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*lEQGuOY31GiJWLfg5x-2gQ.png" /></figure><p>Pausing in the byebug again, we can check our user instance <em>after</em> that user has been updated with their avatar. Remember however, that avatar is not an <em>attribute</em> of a user, rather an <em>attached file</em>. If we check the value of avatar_url we can see that one has been created.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KmRXKotuhvfrU-JMH1TGzQ.png" /></figure><p>Let’s also check out our database, just to be sure…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9-mJLmdSkkNugEE07XfToA.png" /></figure><p>Our new user from above (with an id of 18) does indeed have an avatar attached! The blob_id of that avatar is 10 — so let’s check our blobs table to be sure that it’s in there…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6nN1Lk2bTj6ArvkyqAFleA.png" /></figure><p>And there’s blob 10! Awesome! We have successfully uploaded a file from our user, <em>and </em>attached that file to that user! Now we can go back to the frontend and use that information from our fetch call to set state for our CurrentUser and CurrentAvatar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oRTHJIlQyVaqIEKsCv6hIw.png" /></figure><p>In our App Component we can write a function, updateCurrentUser() that will take the data we receive from that fetch call, and set state with our new information. We will then pass down that function, as props, to the CreateAccount Component. Last but not least, let’s change the last part of our fetch call to invoke that function with the data we get back…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/840/1*ApDVEHiV-zM2MQAo-KxPgQ.png" /></figure><p>Now create a user, and then click on the link to go to that users profile page…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h0dggzGQt-F6nsWCVoBUIw.png" /></figure><p>Bam! Lookin’ good, Harrison.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84e7978ba11d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Connect Your React Application to a Rails API Using Active Storage (part 1)]]></title>
            <link>https://medium.com/@jennyjean8675309/connect-your-react-application-to-a-rails-api-using-active-storage-part-1-e59dcacc481b?source=rss-760302d1b208------2</link>
            <guid isPermaLink="false">https://medium.com/p/e59dcacc481b</guid>
            <category><![CDATA[postgresql]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[active-storage]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[avatar]]></category>
            <dc:creator><![CDATA[Jennifer Ingram]]></dc:creator>
            <pubDate>Wed, 04 Sep 2019 16:50:29 GMT</pubDate>
            <atom:updated>2019-09-09T21:09:00.736Z</atom:updated>
            <content:encoded><![CDATA[<p>Several weeks ago I set out to learn all about web sockets. If you’re thinking that something must have derailed me, because this blog isn’t <em>about</em> web sockets, you’d be correct. I wanted to show off my app’s users on the frontend by giving them each a little avatar. It seemed easy enough to do — I had heard about many people using this thing called Active Storage with Rails to connect image files to a model — so I thought, ‘Hey! I’ll just get this little bit working real quick before I move on to web sockets!’ After falling down a huge Internet rabbit hole of documentation, blogs, Stack Overflow, and many more random sites, I’ve finally found a working solution. So now I present it to you, my friends, hoping that you can avoid the pain I went through.</p><h3>Setting up the Backend</h3><p>My Rails backend will only be used as an API to send and receive information from my database to and from my frontend. For this project, I’m going to use PostgreSQL for the database. From your terminal enter</p><pre>rails new avatar_app --database=postgresql --api</pre><p>*Note — you must have PostgreSQL installed on your computer and running for this command to work.</p><p>Now let’s get Active Storage all setup.</p><pre>rails active_storage:install</pre><p>This command creates a migration file for you that will populate your database with two new tables — active_storage_blobs &amp; active_storage_attachments. According to <a href="https://api.rubyonrails.org/classes/ActiveStorage/Blob.html">Rails documentation</a> —</p><blockquote>“A blob is a record that contains the metadata about a file and a key for where that file resides on the service.”</blockquote><p>The active_storage_attachments table is a join table that connects the blob with the model it belongs to (technically, it’s a <em>polymorphic</em> table, but I prefer to think of it as a simple join table).</p><p>Before we migrate these migrations, let’s add a user model to our application. This app is going to be super simple — user’s will be able to create an account, upload an avatar, and show off their avatar — that’s it!</p><pre>rails g resource User</pre><p>This command does a few things, including giving us a migration file to create a users table — so let’s fill it out.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1010/1*q5lSUpc5jJ0pjBaSBLQDYQ.png" /></figure><p>Notice that even though each user is going to have an avatar, we didn’t include that as a column on our users table. Instead, on our user model, we’re going to indicate that each user will have an avatar attached to it (in the form of a file) like so —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/700/1*3v3dwBXdu2oQk7GWRO7E0A.png" /></figure><p>Before we forget, let’s run those migrations —</p><pre>rails db:create<br>rails db:migrate</pre><p>Because we’ll only be running our Rails API from a local server, we don’t need to do any additional configuration here. If however, you want to set up active storage to keep your files on a remote server — such as Amazon S3, Microsoft Azure, or Google Cloud — there are special instructions for how to do that in the <a href="https://edgeguides.rubyonrails.org/active_storage_overview.html#amazon-s3-service">Rails documentation</a>.</p><p>Before we move on to uploading an image file from the frontend, I think it’s important to show you how to attach a file to a model from your backend. Let’s move into the seeds.rb file, to create a new user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yGXV1-eXxlI_G5L7a8r8ZA.png" /></figure><p>Now, if I want to attach an image file to Lucy from my backend, that image file must exist somewhere within my backend directory. It makes most sense to me to place a folder, called <em>avatars</em>, inside of my <em>public</em> folder. Then I’ll drop my image files in there.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/594/1*aER_SGnSyedQrwCNbLULcw.png" /></figure><p>*If you’re looking for free avatar icons to play around with, here’s a <a href="https://www.flaticon.com/free-icons/avatar">great site</a> (mine came from this site and specifically <a href="https://www.flaticon.com/authors/freepik">this author</a>).</p><p>Awesome! Now let’s attach one of those images to our user named Lucy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yJg-GBC91raxvGxVWRIvfA.png" /></figure><p>Because we’ve already declared in our User model that each user has_one(avatar)_attached, now we can use Active Storage’s attach method to attach the file we want. Notice that the path given to File.open() matches the location of my file in my directory — if you choose to place your image in a different location within your directory, your path will need to reflect that.</p><pre>rails db:seed</pre><p>If we’ve written our seed file correctly, we should see our user, our active_storage_blob, and our active_storage_attachment in our database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DmCfsdQ8dtO595mQ7RGziw.png" /><figcaption>Here’s our user, Lucy!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jmkqUOvh1Z418l-7wxAmWg.png" /><figcaption>Here’s our blob!</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xCxEvWuYUARI22JEcVSszQ.png" /><figcaption>And here’s our attachment!</figcaption></figure><p>Cool, cool, and cool.</p><p>Now let’s setup the wiring that will allow our React frontend (which we haven’t created yet) to communicate with our API. First, let’s make a controller for our User model.</p><pre>rails g controller Users</pre><p>Now let’s fill out the controller actions we’ll need for our application.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/1*6mwAlVKWMW5-AmeDAg6SQg.png" /></figure><p>I’ve filled out the index action to render all users, but I’m going to leave our create, show and update actions blank for now. We need to do just a couple more things to let our frontend and backend communicate smoothly. First, uncomment the ‘rack-cors’ gem in your Gemfile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bvhtUe6SvLEBKnOkXRnZhg.png" /></figure><p>Then, inside of <em>config</em> &gt;&gt; <em>initializers</em> &gt;&gt; cors.rb, uncomment the following code, and change line 10 to read like so…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7XbzqM5w1CKpt_3Le5BaFg.png" /></figure><p>Then re-run</p><pre>bundle install</pre><p>to install that ‘rack-cors’ gem.</p><p>Finally — let’s move on to the fun part — the frontend!</p><h3>Setting up the Frontend</h3><p>To create a React app from scratch, enter the command</p><pre>npx create-react-app avatar_app_frontend</pre><p>from terminal. Then cd into that directory and open up your code. In order to use Rails’ Active Storage with React (a JavaScript framework), we need to install it through our node package manager (npm) —</p><pre>npm install activestorage</pre><p>My app will only allow a user to do one of two things: first, if they already have an account, they can ‘login’ (with fake authentication) and see their avatar on their profile page, else, they can create an account, upload an avatar (image file), and then see their avatar on their profile page. Reply to this post if you’d like to offer a ton of moolah to support this startup.</p><p>Because I would like to create some routes in my application, I’m also going to install react-router-dom.</p><pre>npm install react-router-dom</pre><p>Here is a quick demonstration of how my app is set up, including routes to the various pages, that, as of yet, don’t show much. I’m going to save us a bit of time by not going to go into the deets of how to build this out in this post.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FUp0uOWS6C9U%3Ffeature%3Doembed&amp;url=http%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DUp0uOWS6C9U&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FUp0uOWS6C9U%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="640" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cc3db0ef3b7f583bafb2bce2ef246d1c/href">https://medium.com/media/cc3db0ef3b7f583bafb2bce2ef246d1c/href</a></iframe><p>Now we’ll go ahead and build those pages out, beginning with a login form.</p><h3>Getting Images from the Backend</h3><p>Here’s a login form all built out — almost. If you’re familiar at all with React controlled forms, this should look pretty familiar to you…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TaNVUZ12kkODxNPMdOlXtQ.png" /></figure><p>We have a form with two input fields, one for the user to enter their name, and the other to enter their password. Both inputs are using the onChange event listener, and both listeners call on the handleOnChange() function. This function is changing local state as the user types in those input fields. Finally, when the user hits submit, we call on the handleSubmit() function.</p><p>Let’s think for a moment about what this function needs to do. In order to login a user, it needs to communicate with our backend and find the user with the (kinda fake) credentials they’ve typed in, then return that user to us. When we get that user, let’s set them as the CurrentUser (in state) for our application. We <em>also</em> want to grab that user’s avatar from the backend, so let’s set that piece of state as well. Because different pieces of our application need that information, let’s set state for those things in our App Component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/510/1*sz3Cpg36IEDkU0gjIMUNsg.png" /></figure><p>Okay, now going back to our handleSubmit() function in our Login Component, let’s build out the fetch call that will communicate with our Rails API. The first thing we need to figure out is what url to make the fetch call <em>to. </em>If we enter the rails routes command in our terminal, we see that we can’t make a GET request to our users controller’s show action, without knowing a user’s id, and we actually need to give our application some information (the user’s credentials).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*px-N883ZmXt4To81tdxeTQ.png" /></figure><p>This can mean only one thing… we need to make a custom route!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/900/1*8Mlp7_KTwALqmMMHKcksCw.png" /></figure><p>Cool. Now we have a route to fetch to. Place a byebug in your users controller’s show action, and finish building out your fetch call like so</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/834/1*Q_Y5_wFaSiUZO9CQv2lZjA.png" /></figure><p>If you go to your frontend and try to login our user, Lucy, you should be paused in the byebug from your users controller. Let’s check what params are at this point…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CW9EgFbF9D_QUmbLhAJ9VA.png" /></figure><p>Great! Using those params we can find our user.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dTvWwwgLVJhgrGCgpR2pOA.png" /></figure><p>Now if we log Lucy in with the correct credentials, we see her user object logged into the console, and if we try to log her in with incorrect credentials (i.e. a bogus password) we get the ‘This user is not authenticated’ message. Perfect! We know that we can use this information to set state for our currentUser, but how can we get her avatar?</p><p>Well, conveniently enough, <a href="https://edgeguides.rubyonrails.org/active_storage_overview.html#linking-to-files">Rails provides us a url</a> that we can link to do just that — rails_blob_path. This is how we can use it to pass Lucy’s avatar (or a link to her avatar image) to the frontend…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*9bgI3DdywATcHAoposFefQ.png" /></figure><p>Now on our frontend, we see not only our user object logged into the console, but also her avatar url.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_eDCZuXKsBN5JgSk47bUKw.png" /></figure><p>Awesome. Let’s use this to set state in our app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5etI7V5naAPtXEujpSskhg.png" /></figure><p>In our App Component, we have to make a few changes — first, we need to write a function, setCurrentUser(), that will take in the result from our fetch call (data), and set state for our CurrentUser and CurrentAvatar. Then, we need to pass that function down as props to our Login Component. In order for the Login Component to receive props, we need to change how we render that component.</p><pre>render={() =&gt; &lt;Login setCurrentUser={this.setCurrentUser} /&gt;}</pre><p>Then, in our Login Component, rather than simply logging our fetched data to the console, we’ll call on our function (passed down as props).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/816/1*uxEP-Kfztn1KxVKZbp_p3Q.png" /></figure><p>Now our app has the information it needs to render Lucy’s avatar on her profile page. Let’s build that out!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6qsyMx4ZolS6JgiL8-WRDg.png" /></figure><p>First, on our App Component, let’s import the withRouter function from react-router, and then add some conditional logic on our Profile Component. If this.state.CurrentUser exists (meaning we have someone logged in), then we’ll show the profile page and pass down our current user’s information as props, else, we’ll re-render our Login Component. Also, notice that I’m passing through Route props with my /login route as routerProps. I’ll use this after my user logs in to redirect them to their profile page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/886/1*1b8zgroyAjM5QYwY7QNGjQ.png" /></figure><p>Now, let’s build out our Profile Component to actually show our user’s information…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xptzoPKhFsIm-Jim1sl16Q.png" /></figure><p>Notice that, in order to display our user’s avatar, we have to provide the full path (prepending the actual domain address of our server, which for us is <a href="http://localhost:3000).">http://localhost:3000/).</a> Now, when we log Lucy in, we go directly to her profile page, and … we see her avatar!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CvMHMc7xfmzVIy1tmERwiA.png" /></figure><p>Awesome! Now we have the ability to grab our users’ avatar images from the backend — but that’s only half of what we’d like to accomplish. In part 2 of this post, I’ll show you how to allow a user to upload an image from their own computer, and store it on the backend. Stay tuned!</p><p>You can find part 2 of this post <a href="https://medium.com/@jennyjean8675309/connect-your-react-application-to-a-rails-api-using-active-storage-part-2-84e7978ba11d">here</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e59dcacc481b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Web Scraping with Ruby and Nokogiri]]></title>
            <link>https://medium.com/@jennyjean8675309/web-scraping-with-ruby-and-nokogiri-73e75a6f34ed?source=rss-760302d1b208------2</link>
            <guid isPermaLink="false">https://medium.com/p/73e75a6f34ed</guid>
            <category><![CDATA[nokogiri]]></category>
            <category><![CDATA[web-scraping-tools]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[web-scraping]]></category>
            <dc:creator><![CDATA[Jennifer Ingram]]></dc:creator>
            <pubDate>Fri, 26 Jul 2019 21:33:38 GMT</pubDate>
            <atom:updated>2019-07-26T21:33:38.137Z</atom:updated>
            <content:encoded><![CDATA[<p>Application Program Interfaces (or APIs) are amazing — with them, HUGE amounts of data can be shared across the web and used by programmers to create or enhance an endless variety of applications. For example, a friend and I wanted to create a CLI trivia game — rather than writing hundreds of trivia questions ourselves (which would have taken FOR…EV…ER), we used the <a href="https://opentdb.com/api_config.php">Open Trivia Database</a>, which someone had already toiled on, and pulled in pre-written questions (and answers) to use in our own project. Some APIs, like the <a href="https://developers.google.com/maps/documentation/">Google Maps API</a>, are used by hundreds (thousands? tens of thousands?) of developers to embed maps into their own websites. But what happens if you find a really great website with tons of cool information but there is no API?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/365/0*9Gb5g5KOyLi8RgyO.gif" /><figcaption>Aww… it’s okay little guy.</figcaption></figure><p>Web scraping to the rescue!</p><h3>Web Scraping</h3><p>Web scraping is exactly what it sounds like — it involves scraping the web (or more precisely, the <em>HTML</em> on the web) with a fine-toothed comb to grab the information we need.</p><p>When we navigate to a website, say <a href="http://www.nytimes.com,/">www.nytimes.com,</a> the HTML that makes up that website is readily available to us. Don’t believe me? Navigate to said page, and (if you’re on a Mac), go to the View menu, select Developer from the drop-down menu, then select Inspect Elements. When you do that, a nifty box will appear either to the side or the bottom of your web page. It’ll look something like this…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2MJImWQIteoCQJDB6rf_nQ.png" /></figure><p>The HTML you see in the tool box is the very same HTML that’s currently being rendered by your browser in the browser window. Take a moment to poke around and become familiar with it. We’ll be using the Developer Tool Box quite a bit in this post. With your Elements tab open, find the little box with the arrow pointing at it at the top menu of your Developer Tool Box. Go ahead and click on that…</p><p>Notice that if you now hover over any segment of the webpage with your cursor, certain bits will be highlighted. If you then click on that highlighted segment, the highlight on the text disappears but now a section of the HTML in the Elements window is highlighted! This piece of HTML correlates with the element you highlighted in the text. This element-selecting tool is indispensable when it comes to scraping the web.</p><p>In the next few sections, I am going to create a database using Ruby on Rails, and seed my database with information scraped on the web. Feel free to code along if you’d like!</p><h3>The Target</h3><p>M y goal is to build a web app that allows users to see information about all of the museums in Idaho. In order to do this, it’d be really nice to have a database that holds that information. Museumsusa.org is a great site that has a huge collection of museum information, searchable by state. Perfect! We’ll use this. Here’s the page that shows a list of cities in Idaho that have museums…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*l8S2r0eiMuS3NskECRXDmQ.png" /></figure><p>When I click on a city (i.e., Boise), I see a page that lists information about all 10 museums in Boise, Idaho — including the museum name, its city and state, a category (or list of categories) that it belongs to, and a brief description. This is all great stuff — we’ll focus on scraping this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hGP0epntXy9iMa_3lzAgmA.png" /></figure><h3>Setting Up the Code</h3><p>First, let’s setup a new api Rails app from the terminal…</p><pre>rails new idaho_museums --api</pre><p>The first thing I’d like to start with is setting up a model for my museums.</p><pre>rails g model Museum</pre><p>This creates a museum.rb file inside of app/models, <em>and</em> a migration file inside of db/migrate. Let’s go ahead and fill out the columns for the museums table, using the information we know we can get from the museumsusa.org website. When all filled out, our migration will look like this…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mtHqIltBLhm75TMa8YWCvw.png" /></figure><pre>rails db:migrate </pre><p>The last thing we need to do before we begin scraping is to place the nokogiri gem in our Gemfile, and run bundle install to install that gem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mubC08klTn9cWKpLyIryyw.png" /></figure><pre>bundle install</pre><h3>Creating the Scraper</h3><p>Awesome. Now we’ve got everything set up to build out our scraper. We’re going to do this by creating a separate Scraper class in app/models. Our Scraper model will need do to a few things — first, we need to collect all of the urls for each city from our main Idaho museums page — then, using those urls, we will navigate to each city’s page, and from each city’s page, we need to create an instance of museum using information we scrape from the HTML of that page. This sounds like a lot, so let’s tackle it one step at a time.</p><p>Create a file named scraper.rb in app/models. We’ll be using both nokogiri and open-uri, so we’ll require them both at the top of our file. Note that we didn’t need to install open-uri — that’s because open-uri comes as part of the standard Ruby library, and it is <em>not</em> a gem, so we don’t place it in our Gemfile.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/658/1*-NIpb9r57K13zmHLxPsm2g.png" /></figure><p>Our base_url (the one that lists all of the cities in Idaho) is found at ‘http://www.museumsusa.org/museums/?k=1271400%2cState%3aID%3bDirectoryID%3a200454&#39;. I can use open-uri’s open method, which takes in one argument, a URL, to return to us the <em>HTML content of</em> that URL. Next, we’ll use the Nokogiri::HTML method to return the HTML we just created as a set of nested nodes, that we can then explore. This method also takes one argument, the HTML that we returned from our open method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*I-frKE1WANX8h2V2rNUXCA.png" /></figure><p>By creating a new Scraper instance at the bottom of our file and dropping a binding.pry inside of our class, we can run</p><pre>ruby app/models/scraper.rb</pre><p>and drop into the pry from our terminal. From here, we can check out the value of our doc variable. Cool, huh?</p><h3>Unlocking the Power of Nokogiri</h3><p>Nokogiri allows us to use CSS selectors to scrape our pages. To do this, we’ll use the #css method on our doc variable, and pass in as an argument the CSS selector we want to target. Let’s go back and inspect our webpage…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*winDcKjjzmUXiC2rbsPA2Q.png" /></figure><p>Here I see three different &lt;div&gt;s with a class name of browseCategory. I want the one in the middle that holds the table of city names. Inspecting that element, I see that the table has an id of ‘city’ — this seems like a great place to start.</p><p>Now I’m going to refactor my code in scraper.rb just a bit, nesting everything that I’ve already written into a function that I’ve named scrape_city_urls.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-AhmRgas5y0IZY5vI6zUjw.png" /></figure><p>Notice how I’ve used the #css method…</p><pre>doc.css(&#39;#city&#39;)</pre><p>If you’re familiar with CSS selectors, you’ll know that a . denotes a class, a # denotes an id, and a plain text word (like img) denotes a tag. If city were a <em>class</em> name, I would pass the argument like this…</p><pre>doc.css(&#39;.city&#39;)</pre><p>Hovering over my targets (the links to every city’s page that holds that city’s list of museums), I can see that the cities are listed as rows in a table. Each row has a class name of browseCategoryItem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*60t_tU_hXllytc2EsYIInQ.png" /></figure><p>We can chain our #css methods together like so…</p><pre>doc.css(&#39;#city&#39;).css(&#39;.browseCategoryItem&#39;)</pre><p>So now we’re telling nokogiri to look inside of the &lt;div&gt; with an id of ‘city’ and collect all of that &lt;div&gt;s nested nodes with a class name of ‘browseCategoryItem’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*WLL5Qy-6zrYtNCNRYpqRrQ.png" /></figure><p>At the bottom of my page I’m now calling my newly written method on the instance of scraper that I’ve initialized. Dropping into pry, I can now check the value of cities…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gu6FEVblEeN6QB9OJxYg1g.png" /></figure><p>Woah! That’s a giant mess! But, if we look carefully, we can see that this giant mess is an array, and we can see that there are anchor tags (&lt;a&gt;s) in there with href (hyperlink references) that point to urls. We’re close! Because those anchor tags are what we’re really after, let’s chain another CSS selector onto our query.</p><pre>cities = doc.css(&#39;#city&#39;).css(&#39;.browseCategoryItem&#39;).css(&#39;a&#39;)</pre><p>Now let’s check the value of cities.first to grab just the first item in that array…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fMGB-3OmrPCXfIa6dLUepw.png" /></figure><p>Awesome! Now we have access to each &lt;a&gt; tag for every city, through our array. And because cities <em>is</em> an array, we can iterate through it using an #each method.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ArYKOnhvHTnWqbWmHy49zg.png" /></figure><p>Because every instance of city is an HTML node that refers to an &lt;a&gt; tag, we can now use a different method provided by nokogiri, #attribute, that allows us to grab an attribute of an HTML node by name (‘href’), and then, using the #value method, grab its value.</p><p>Dropping into pry now, we see that our url variable returns exactly that — the url!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m5hCLfb7ZEZEawZa3_HmFg.png" /></figure><p>My next step is to shovel those urls into an array, city_urls, and then check the value of that array, by puts-ing it out to the console.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7yzZHcqH1lFtDdLkzM5yrw.png" /></figure><p>Awesome! The first task that we wanted our scraper to accomplish (collect all of the urls for each city from our main Idaho museums page) is done! Let’s move on to the next step — using those urls, navigate to each city’s page.</p><p>Here, I’m going to create a new function that will handle our next step. Rather than puts-ing out our city_urls array at the end of my scrape_city_urls function, I’m now going to pass that array into my new function, which I’ll name scrape_city_pages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Tu-FN8lgFnOe2y_lP7B3pQ.png" /></figure><p>Now that we have access to our urls inside of this function, how can we open them up to inspect the HTML inside? Remember the #open method provided by open-uri? Let’s use that!</p><p>Our urls at this point are actually not complete. They look like this…</p><pre>/museums/?k=1271404%2cCity%3aJerome%3bState%3aID%3bDirectoryID%3a200454</pre><p>So to get the full url path we need to start with the domain name (museumsusa.org), and then, using interpolation, we can pass in each city’s incomplete url as we iterate over our city_urls.</p><p>Just as we did before, we’ll use open-uri and nokogiri to give us access to the HTML of those pages.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Gab5bG9daBlHMsR52KAu9Q.png" /></figure><p>Dropping back into our pry, we can now see that the value of doc is a new list of nodes that we can explore.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QAu7XWqHMDb0kmbeGP1w4A.png" /></figure><p>Looking down through the attributes, we see that this HTML is specifically related to museums in American Falls, Idaho — the first city listed for Idaho. Perfect! Let’s navigate to that page in our browser and inspect it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CtOAvQnThNOHssFvAMohvA.png" /></figure><p>American Falls only shows one museum, and that museum is rendered in a &lt;div&gt; with a class name of ‘itemGroup’. But because what I ultimately would like to do is pull out the information for <em>all</em> museums listed on a city’s page, I’m going to navigate to a city that has a list — how about Boise?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*N39PwsVqiRnO5hZUUFpiKw.png" /></figure><p>The Boise page also includes a &lt;div&gt; with a class name of ‘itemGroup’. That &lt;div&gt; has children &lt;div&gt;s that have two class names — ‘item’ and ‘basic’. If I open up one of <em>those</em> &lt;div&gt;s I can now see the information I want to target — the museum name, it’s city and state, it’s type, and a short description. To translate this into code, we’ll now have…</p><pre>doc.css(&#39;.itemGroup&#39;).css(&#39;.item&#39;).css(&#39;.basic&#39;)</pre><p>Notice that I separated out the div that held two class names (‘item’ and ‘basic’) into two different css selectors.</p><p>Now let’s set a variable, museums_list to an empty array, and as we iterate over our city_urls to grab those &lt;div&gt;s , let’s shovel them into that array — what we hope to end up with is a collection of &lt;div&gt;s that each hold the museum information we need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XOmGWVFKs1icqqQesI2Mgg.png" /></figure><p>Now re-run your scraper in your terminal so that we can drop back down into our pry.</p><p>… waiting … waiting …</p><p>Did you notice how long that took?!!! Your computer is working hard — scraping is an intense process, especially as we’re using loops within loops to get the information we want. After the process eventually finishes, museums_list should hold exactly what we need.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UXK-BpJ_RlMaMx9WVYOpRg.png" /></figure><p>Hang in there — we’re almost done.</p><p>Now we’re going to create another function, which I’ll name create_museums. This function will take an argument, our list of museum nodes, and be responsible for scraping the information we need from each node to create a museum object in our database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*4094MUOslrVXAMDKpgmV1A.png" /></figure><p>Now we can drop back into pry, and experiment with our museum variable.</p><p>Going back to our inspector tools, we can see that our museum’s name is included as the inner text of an &lt;a&gt; tag, which is nested inside of a &lt;span&gt;, which is nested inside of a &lt;div&gt; with a class name of ‘source’.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_ngeuX3nez1BiDVUerRphg.png" /></figure><p>Let’s test this out in our terminal…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K1Nonwq4HYKCTHvWEvqQww.png" /></figure><p>Yes! After all of that scraping we finally have some clean, usable data! Now we can go in and add the code to return our museum’s name, as well as it’s location, type, and description.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*yj6pR5BcbKjmqoJ1NXRrHA.png" /></figure><p>Notice that for location, because we want to store both the city and state separately, we can simple split our location string (“Some City, Some State”) on (, ), turning our string into an array that we can pull those values from separately.</p><p>I <em>highly recommend</em> checking the values for name, location, type, and desc in your console before the next step.</p><p>Now, for each museum, we’re going to create a museum_info hash that we’ll use later to save our museum information to our database. I’m going to set an empty array, museums, and shovel each museum_info hash into it. Our create_museums functions, when all done will look like this…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ove_ew59xGS0Zqbh5otwIA.png" /></figure><p>Now, instead of running our scraper from inside of our scraper.rb file, we’re going to make a few adjustments so that we can seed our database using our scraped information.</p><p>First, we want to give our Museum model the ability to create instances using the array of museum_info hashes we just created. We’ll define a class method, create_museums_from_collection that will do just that.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1U7cXDkiWNX5GY4iFcKtVg.png" /></figure><p>Now we’ll jump on over to our seed.rb file, found in our db folder, and run our scraper from there to seed our database.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/972/1*fIfjn5XyGP1DJ08giZ6jrA.png" /></figure><p>Now, jumping back to our terminal, all we have to do to seed our database is run</p><pre>rails db:seed</pre><p>and… voila! We are now the proud owners of a beautiful museum table that holds all of our scraped objects!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*d03VnO9d-2Dl4wiWEN_cjA.png" /></figure><h3>The Downside</h3><p>Web scraping is really useful… we did, after all, just grab a <em>lot</em> of useful data from a webpage that we can now use on any web application we want. The downside of scraping is that, if the developers of the site that we just scraped were to redesign it — rearrange content, rename things, delete things… our scraper would no longer work. This means that, unlike an API, where developers can easily fetch any updates to their data, this process is a lot harder, or may even be impossible, when scraping. But, if you’re hoping for a one-and-done process and are only concerned with initializing data, like we did here, then scraping may be a great option.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=73e75a6f34ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring JavaScript’s Reduce() Method (Part 2)]]></title>
            <link>https://medium.com/@jennyjean8675309/exploring-javascripts-reduce-method-part-2-85df5010aabe?source=rss-760302d1b208------2</link>
            <guid isPermaLink="false">https://medium.com/p/85df5010aabe</guid>
            <category><![CDATA[frequency]]></category>
            <category><![CDATA[reduce]]></category>
            <category><![CDATA[anagram]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[hash]]></category>
            <dc:creator><![CDATA[Jennifer Ingram]]></dc:creator>
            <pubDate>Tue, 23 Apr 2019 00:15:06 GMT</pubDate>
            <atom:updated>2019-05-08T19:14:44.096Z</atom:updated>
            <content:encoded><![CDATA[<p>I recently wrote a <a href="https://medium.com/@jennyjean8675309/exploring-javascripts-reduce-method-part-1-84a8e804020e">blog post about JavaScript’s reduce() method</a> in which I laid out the basics for a fairly solid, foundational understanding of this common method. In that post I detailed reduce()’s arguments — a callback function, also called a <strong>reducer</strong>, and an optional <strong>initialValue</strong>. The <em>reducer itself</em> also accepts four arguments — the first two, <strong>accumulator</strong> and <strong>currentElement</strong>, are required, but the other two, <strong>currentIndex</strong> and <strong>array</strong>, are optional. If you feel you need a quick refresher on how reduce() works, feel free to read my earlier post, or check out the MDN documentation <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/reduce">here</a>.</p><h4>The Fun of Frequency Distribution</h4><p>One of the awesome things about reduce() is that it can be used to do so much more than add or subtract the elements of an array. One of my favorite topics as a newbie programmer is <strong>frequency distribution</strong>. When you ask about a value’s frequency distribution, you’re basically asking, ‘How often does that particular value occur?’</p><p>To give you an example, the string ‘supercalifragilisticexpialidocious’ contains 34 letters. But how many times does each letter occur within the string?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/435/1*T7GjnJZhBXMj1QvDfmYvgg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*UXHCQsIG1bhpOvrs" /></figure><p>Let’s used reduce() to figure it out (’cause unfortunately, I can’t snap my fingers to magically produce the result).</p><p>First of all, reduce() is an array method, and can’t be used on strings. So, our first step will be to turn our string into an array.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/233/1*6T4w48NOmVXT42x4xw-vLw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*NitodPJHOZxma9_zsJ5v-g.png" /></figure><p>The split() method iterates through our string, splitting up each character (designated by our empty quotes as an argument) and placing them as elements in a new array. Now that we have our array, we can call reduce() on it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/269/1*jryl1n0Ae6tgkqBZ9Z3DDA.png" /></figure><p>Remember that reduce() takes two arguments, a callback function (or <em>reducer</em>), and a second, optional argument, an <em>initialValue</em>. In the code above, my reducer ( (acc, cur) =&gt; {} ) accepts two arguments, acc (short for <em>accumulator</em>, and cur (short for <em>currentElement</em>). The reducer is followed by a second argument, or initialValue, which I have set to an empty object({}).</p><p>We’re going to open up those curly braces on our reducer and continue writing our code in that block.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/513/1*bksyf1Deru78qxDzv8ABtQ.png" /></figure><p>Remember that, if we set an initialValue, on our first iteration our accumulator is set to that initialValue ({}) and our currentElement will begin with the first element in our array (‘s’). Perfect! That’s exactly what we want.</p><p>The hash that we create will have all of the non-repeating letters of our array as its keys, and the values of those keys will be the number of times that that letter appears in our array. Let’s see how to create those keys in code…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/316/1*GcJEM8I3KifKG_QRodiMBw.png" /></figure><p>On our first iteration through the reduce() method, the accumulator is set to {}, our initialValue. With each iteration through the characters in our array, we want to check and see if that character already exists as a key in that hash (if !acc[cur]) — if it doesn’t, we want to create that key, and set its value (or current count) to 1 (acc[cur] = 1).</p><p>Simple enough! Now let’s finish out our code…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/320/1*kqfvylskfB1t9YCTlTmAHw.png" /></figure><p>Here you’ll see that I’ve added an else statement to what we’ve already written — so, if our key doesn’t exist, we create it and start our count to one, <em>or else, </em>if we have already encountered this character before (and thus made a key), we want to increment our count by one (acc[cur] += 1). You’ll notice that I’ve set this method to a variable called hash — this is simply so that I can print the results out to my console with console.log.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/75/1*Z9j7gaZlZ4DZY5jwc3mNcw.png" /></figure><p>And … voila! A beautiful hash showing the frequency distribution of all of the letters in supercalifragilisticexpialidocious.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/0*tkcm_0FRbZ1OvyT8" /></figure><p>Why is this fun? Well, now we can answer a whole bunch of questions about our string. Which letter occurs the most? The letter ‘i’ of course! How often does it appear? 7 times! More than twice as much as the next most frequent letters!!!</p><p>Still not excited? Let’s look at something <em>really</em> cool — like anagrams!</p><h4>The Fun of Anagrams</h4><p>An anagram is a word that can be formed by rearranging the letters of another word. For example, <em>tar</em> is an anagram of <em>art</em>. Both words use the same three letters, with the same amount of frequency. Are you seeing how we might use our newly created hash to check if a phrase is an anagram of another word? Exactly! If our phrases have the same frequency distribution of letters then they must be anagrams.</p><p>Here is an example anagram for ‘supercalifragilisticexpialidocious’ that I found from <a href="http://www.anagramgenius.com/archive/superc.html">this website</a>. Let’s use our newly created (and super duper cool!) tool to test it!</p><p>The example anagram is ‘Luscious fig lips expel idiocratic aria.’</p><p>Now this one’s a bit tricky because we have some spaces, capitalization, and punctuation in there. Not to worry though — we can handle those easily enough.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/521/1*mXikgKpgilogW7d0F0M4Nw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/1*w8FVcPTMDZDTv9hIMrO1rg.png" /></figure><p>In the second line of code, we can use JavaScript’s replace() method to replace all of the spaces in our string with… nothing — removing them, in other words. The forward slashes (//) in the code denote a <strong>RegExp</strong>, or Regular Expression. Whatever pattern you want to replace goes inside of those forward slashes — in our case, just a space. The little g on the outside (which stands for global) tells the replace() method that we want to replace <em>all </em>of the spaces in our string (if we didn’t include the g it would only replace the first one). Last but not least, the empty quotes tell replace what exactly we want to replace those spaces with. The result is…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/417/1*RwTjgJxsc37p5aN2zTAzGw.png" /></figure><p>Now we need to remove that period at the end.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/352/1*Q5lZ24CvA-T0mQeFXClBHA.png" /></figure><p>Notice that here I’m not using a RegExp. That’s because I know I only need to remove the one period at the end of the sentence. And finally, to make all of our letters lowercase, and to turn our string into an array…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*vebHZUwO7ALWE53D-e90TQ.png" /></figure><p>Great! Now our array is all prepped, and we can use our reduce() method to see what the frequency distribution of the characters is…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/475/1*Vu27QOicpXn2jscr4_rFyA.png" /></figure><p>Now, the final test… does the frequency distribution of ‘supercalifragilisticexpialidocious’ match the frequency distribution of our (alleged) anagram?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/429/1*318zrBupFbHsfIaQjwi_1g.png" /></figure><p>If the for loop prints out ‘true’ for every character in our hash (which it does), then we have a match! and our example is indeed, a <em>certified</em> anagram. Yay!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/0*RNKuHm6hv3vksRLF" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=85df5010aabe" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring JavaScript’s reduce() Method (Part 1)]]></title>
            <link>https://medium.com/@jennyjean8675309/exploring-javascripts-reduce-method-part-1-84a8e804020e?source=rss-760302d1b208------2</link>
            <guid isPermaLink="false">https://medium.com/p/84a8e804020e</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[methods]]></category>
            <category><![CDATA[reduce]]></category>
            <dc:creator><![CDATA[Jennifer Ingram]]></dc:creator>
            <pubDate>Tue, 19 Mar 2019 18:57:52 GMT</pubDate>
            <atom:updated>2019-03-19T18:57:52.965Z</atom:updated>
            <content:encoded><![CDATA[<p>According to current <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Methods_Index">MDN documentation</a>, there are 438 documented JavaScript methods. As JavaScript is <em>the</em> language of the web, I’m determined to master it, or at least, you know, try to keep up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*_OufOkpMJ7BUmwU_.gif" /><figcaption>(I’m the old man in this scenario)</figcaption></figure><p>If you’re familiar at all with JavaScript, then you’re probably familiar with JavaScript’s more prominent methods — map(), filter(), the for…in loop, and, if you’ve ever needed to add elements in an array, reduce().</p><p>I’ll admit it — reduce() has always been a bit confusing to me. First of all, it takes in a callback function (queue a slightly uncomfortable, almost panicky feeling), <em>and</em> it has some optional arguments which can drastically change what the method returns. But, after playing around with it for a bit in the console, I’m finally understanding some of its nuances.</p><p>So, let’s dig in and explore, shall we?</p><h4>How to Use reduce() to Add Elements in an Array</h4><p>As I mentioned above, the most common use (I’m guessing) of the reduce() method is to add up elements in an array, so we’ll take a look at that first.</p><p>Let’s say I’m a kid with a jar full of coins, and I’m saving up to buy a brand new box of crayons (IMHO, the best thing ever).</p><p>coins = [1, 5, 1, 5, 1, 10, 25, 10, 25, 1, 1, 5, 10, 10, 5, 5, 1]</p><p>To add all of these coins, we’ll use reduce(). Reduce() takes in a couple of arguments— the dreaded <em>callback function</em>, and an <em>initial value</em>. (The initial value argument is optional, and we’ll take a look at that in just a moment). The callback function doesn’t have to be scary though — it’s actually pretty cool.</p><p>Here’s how it looks…</p><p>coins.reduce( <em>(accumulator, currentElement) =&gt; { }, initialValue </em>)</p><p>Notice that the callback function itself takes in two arguments — accumulator and currentElement. <strong>It’s important to understand that reduce() is a looping method — it runs once for each element in your array. </strong>The <strong>accumulator </strong>is the value returned each time the reduce() method runs. The <strong>currentElement</strong> is, you guessed it, the element currently being looked at as the loop runs. If an initialValue is given, then our accumulator will be set to initialValue on our first run through the loop, and our loop will begin with the first element in the array. So, filling out our reduce() method to add our coins will look like this…</p><p>coins.reduce( (accumulator, currentElement)=&gt;{return accumulator + currentElement}, 0);</p><p>Running this in your console should return 121. So we have 121 cents to apply toward our crayon purchase. Yes!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/322/0*XRVLsrwQpvi2ps15" /></figure><p>Here’s a breakdown of what’s happening when the JavaScript engine runs…</p><p>On our first iteration, because we assigned an initialValue (0), our accumulator is equal to 0, and our currentElement is the first element in our array, 1.</p><p>coins.reduce( (accumulator(0), currentElement(1))=&gt;{return accumulator(0) + currentElement(1)}, 0);</p><p>The value returned from our first iteration is 1 (0 + 1), and on our second iteration, the accumulator is reset to 1.</p><p>coins.reduce( (accumulator(1), currentElement(5))=&gt;{return accumulator(1) + currentElement(5)}, 0);</p><p>The value returned now is 6 (1 + 5), and our accumulator is reset again.</p><p>Notice that the accumulator keeps resetting (or accumulating, eh?) through each iteration of the loop. This keeps happening until our loop finishes with the last element in our array, when it spits out the final value, 121.</p><h4>How Things Change When We Omit an Initial Value</h4><p>Remember how I said that the initial value argument is <em>optional? </em>Let’s take a look at how things change when we <em>don’t</em> provide an initial value.</p><p>coins.reduce( (accumulator, currentElement)=&gt;{return accumulator + currentElement} );</p><p>Hmm… running this in the console returns the exact same value — 121. What’s important to remember is that <strong>even though we get the same return value by omitting the initial value, that omission completely changes how the reduce() method starts</strong>.</p><p>From the MDN documentation —</p><blockquote>If no initialValue is provided, then accumulator will be equal to the first value in the array, and currentValue(Element) will be equal to the second.</blockquote><p>*Just a side note — I prefer to use the variable name currentElement (instead of currentValue) — it just makes the process clearer to me.</p><p>For our coins array, this means that on the first iteration through the reduce() method, our accumulator is equal to 1 (the first value in our array), and our currentElement is equal to 5 (the second value in our array).</p><p>coins = [1, 5, 1, 5, 1, 10, 25, 10, 25, 1, 1, 5, 10, 10, 5, 5, 1]</p><p>coins.reduce( (accumulator(1), currentElement(5))=&gt;{return accumulator(1) + currentElement(5)} );</p><p>This may seem pretty simple, but if you don’t remember that the reduce() method has this unique behavior, then you may get some unexpected returns when attempting to use it in the future.</p><h4>Other Arguments to reduce()’s Callback Function</h4><p>Besides accumulator and currentElement (which are not optional), reduce() also accepts two other (optional) arguments — currentIndex and array. The <strong>currentIndex </strong>is, you guessed it, the index of currentElement, and <strong>array</strong> is simply the array that reduce() is being called on.</p><p>Let’s say I have an array of numbers (numbers = [1, 2, 3, 4, 5, 6]) and I want to add every other number in that array, beginning with the first element. I can use the optional currentIndex argument to accomplish this!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/635/1*IsjLximNRA1JZjF8E9lWBA.png" /></figure><p>In this callback function to reduce(), I have a conditional that is checking the currentIndex — if the currentIndex is even (I’m using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Arithmetic_Operators">modulo operator</a> to check for a remainder), then I will add that element to the accumulator. If the currentIndex is not even, then I won’t add the current element, but just return the accumulator as it currently stands.</p><p>Running this in your console should return 9 — the result of adding 1, 3, and 5 (at indices 0, 2, and 4, respectively).</p><h4>Setting Out on the Wrong Foot</h4><p>Now let’s try adding the other numbers (at indices 1, 3, and 5).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/607/1*He6zeIUBgjdFGh9_nVtdQw.png" /></figure><p>Note that the <em>only</em> change I’ve made here is in our conditional (instead of currentIndex % 2 === 0, it’s currentIndex % 2 !== 0).</p><p>Running this in the console returns 13. Hey! What gives?! 2 + 4 + 6 = 12, not 13.</p><p>So remember that tricksy behavior when an initial value is not provided — here’s what’s happening…</p><p>Our reduce() method is saying, ‘Hey! You didn’t provide me with an initial value! I guess this means you want the first element in the array to start off as the value of the accumulator, and the second element to start off as the currentElement? Okay, sure!’ Our first iteration of the reduce() method now looks like this…</p><p>numbers = [1, 2, 3, 4, 5, 6]</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*4EWR9pB4RgpE04hzU0ZkIA.png" /></figure><p>In this example I’ve plugged in the values from our numbers array according to the rules of the reduce() method. Our accumulator is set to the first element in our array (1), our currentElement is set to the second element in our array (2), and the currentIndex is set to the index of the currentElement (the index of 2 is 1). Our conditional checks to see if our currentIndex (1) is even — it is not — and so our accumulator (1) gets added to our currentElement (2) (1 + 2 = 3), and on the second iteration of our reduce() method, our accumulator is set to 3. This is obviously not what we want, so how do we fix this?</p><p>We add an initial value!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/546/1*U-bZUsca4A6XHzWh7VHUGQ.png" /></figure><p>Running this in the console now should yield the expected result — 12! Yay!</p><h4>Other Stuff You Can Do With reduce() Besides Add (Hint… You Can Subtract Too)</h4><p>Lest I give away the impression that reduce() is really only helpful to add things, let’s explore reduce() just a little bit more.</p><p>Going to back to our I’m-a-kid-buying-crayons story, let’s say that I’m shopping around, and I would like to buy a 64-count box for about $4.23, or 423 cents. *I am not however, going to buy <a href="http://www.neutronusa.com/prod.cfm/2624487/glb?gclid=Cj0KCQjwpsLkBRDpARIsAKoYI8x9wMxrGjP5-RQi-f1iI1-xWwGi9ltFAFL_lIpeaAWYAOr5IpvN-5caAsWjEALw_wcB">this box</a> —</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/754/1*JhGBf8ykYXWonW-1nwwRvg.png" /><figcaption>Kids — always, always shop around for your purchases to be sure you’re getting a good deal.</figcaption></figure><p>Okay, so I’m going to buy the reasonably priced box ($4.23). What I want to know, really, is not how much money I have saved up, but how much <em>more</em> I need to buy my crayons. I can use reduce() to do this…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/569/1*xY1RuhoH8iLSfon2Xf8jGw.png" /></figure><p>Here I set the initial value to 423, and with each iteration I <em>subtract</em> my coins. Pretty sneaky!</p><p>This returns 302 cents, or $3.02. Perfect! Time to go raid the couch cushions one more time…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*VSmrL7DG6tj9eo1_" /><figcaption>I knew my couch was eating things.</figcaption></figure><h4>In Conclusion…</h4><p>There really is so much more that you can do with the reduce() method (hint… it goes waaay beyond adding and subtracting), but the drama of our crayon story was pretty mentally and emotionally exhausting, so I’ll address those in my next blog — Exploring JavaScript’s reduce() Method (Part 2). See you soon…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=84a8e804020e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Considering Optimization and Time Complexity with JS Algorithms]]></title>
            <link>https://medium.com/quick-code/considering-optimization-and-time-complexity-with-js-algorithms-4c8915086518?source=rss-760302d1b208------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c8915086518</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[time-complexity]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[big-o-notation]]></category>
            <dc:creator><![CDATA[Jennifer Ingram]]></dc:creator>
            <pubDate>Fri, 22 Feb 2019 18:25:51 GMT</pubDate>
            <atom:updated>2019-02-25T17:38:08.844Z</atom:updated>
            <content:encoded><![CDATA[<p>After having recently graduated from Flatiron’s Full Stack Immersive Program, I am now armed with a pretty impressive toolbox of languages, frameworks, and methods to take into my new world as a software developer. My goal now is to understand those tools even better, and to reach that level of expertise where I know exactly the right tool to use for each particular situation.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*vQ-lydob-3fWGWGk" /></figure><p>I was recently presented with a whiteboarding question that, on its surface, seemed rather simple: Given an array of positive integers, write a function that returns true if any element in that array is the double of any other element. If not, return false. So, if I were given the array [3, 4, 6] my function should return true, because 6 is the double of 3. Given the array [4, 5, 7] my function should return false, because no number in that array is the double of any other number in the array.</p><p>Thinking through the problem logically, my initial plan was to…</p><ol><li>Determine the double of each number in the array, then</li><li>Check to the see if the array includes any of the doubles.</li></ol><p>This is a fairly straightforward plan, and here’s what it looks like in code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/366/1*fb9AeeUyIl1RCVaMYmDNjQ.png" /></figure><p>This function uses a while loop to iterate through each number in the array (array[i]), then a conditional (if statement) uses the .includes() method to check to see if that number’s double (array[i] * 2) is included in the array. If it finds the double, the function breaks out of the loops and returns true. If not, the while loop continues to run through the entire array, and with each iteration of the while loop the .includes() method runs through the entire array. When no double is found, the loops conclude without returning anything, at which point the function returns false.</p><p>My includesDouble function is easy to read, and easy to understand, but let’s consider time complexity and Big O notation for a moment…</p><h3>Time complexity simply refers to the amount of time it takes an algorithm, or set of code, to run.</h3><p>Time complexity is most often measured in <em>Big O notation</em>. If you’re unfamiliar with Big O, here’s <a href="https://www.interviewcake.com/article/java/big-o-notation-time-and-space-complexity">a great article</a> that breaks it down in simple terms. For my includesDouble function, n, which is the size of the input, would be 3 — if we were to use either of our earlier arrays ([3, 4, 6] OR [4, 5, 7]). So we begin with O(n) = 3.</p><p>When considering time complexity, <em>best practice is to calculate the worst case scenario</em>. Looking at our two arrays, that would be [4, 5, 7], because we know that this array does not include a double, so both loops (our while loop and .includes()) will run completely through the entire array because there is no true case that will break them out of the loops. Okay, so if [4, 5, 7] runs through the while loop we have a linear run time of O(n) = 3, because our while loop runs once for each element in our array (once for 4, twice for 5, and a third time for 7). <em>However, for each iteration of our while loop we have a nested loop that also runs — .includes().</em></p><h3>Beware of nested loops — this is where your time complexity, or Big O notation, begins to grow exponentially.</h3><p>Let me explain…</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/1*fb9AeeUyIl1RCVaMYmDNjQ.png" /></figure><p>If our array includes the numbers 4, 5, and 7, on our first iteration through (where array[i] = 4), our .includes() method is going to run through each item in our array to see if the array includes 8 (array[i] * 2). It will then do the same thing for all of the other numbers in our array (5, then 7).</p><p>To make things more explicit, our JavaScript engine would run through the following steps:</p><ol><li>For the number 4, does 4 equal 8?</li><li>For the number 4, does 5 equal 8?</li><li>For the number 4, does 7 equal 8?</li><li>For the number 5, does 4 equal 10?</li><li>For the number 5, does 5 equal 10?</li><li>For the number 5, does 7 equal 10?</li><li>For the number 7, does 4 equal 14?</li><li>For the number 7, does 5 equal 14?</li><li>For the number 7, does 7 equal 14?</li></ol><p>Because we have a nested loop, our Big O notation goes from O(n) = 3 to O(n²) = 3². A Big O of 3 vs. a Big O of 9 isn’t that great a difference, but remember that with time complexity, we want to consider the worst case scenario — what if our array was a thousand numbers long? All of a sudden, O(n) = 1000, turns to O(n²) = 1,000,000 with a nested loop! Now that’s a big difference! Imagine if our array contained a million numbers!!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/0*mFM7KlNtmvxlLI8m" /></figure><p>So, is there a way to solve this problem with an algorithm that doesn’t use a nested loop?</p><p>I’m so glad you asked, because the answer is yes.</p><p>Enter the hash table…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/300/1*JUJe4U-a7IjB6Br-xg5IQg.png" /></figure><h3>A hash table is simply a data structure that is associative — it maps keys to values.</h3><p>If you’ve been coding for at least a little while, you’ll have seen this type of data structure before — (hash tables are also called objects in JavaScript and hashes in Ruby).</p><p>‘That’s really great,’ you’re probably thinking — ‘but how does a hash table about cats solve the algorithm problem above?’</p><p>Let me share with you the solution first, and then we’ll go through it step by step.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/539/1*QKzxFBv3kK2PaEn0eonDpw.png" /></figure><p>Again, we’ll use our previous array ([4, 5, 7]) to walk through this function.</p><p>On the first line inside the function, notice that I’m declaring a new variable, doubles, and setting it equal to an empty hash table ({}). We’re going to build out this hash table using the elements from our array as we go.</p><p>Just as before, we’ll start with a while loop (O(n) = 3). Inside the while loop, I’m going to use the numbers in my array to make keys for my new hash table (doubles[array[i]] = ‘cats are so cool’). We know that with this array, our while loop will return without returning true, so after our while loop finishes, we’ll have a hash table that looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/231/1*haYVcmnu3DlusdY1f6cq2g.png" /><figcaption>Cats ARE really, really cool.</figcaption></figure><p>Notice that, even though they’re full of wisdom, the values that I’ve set my keys to don’t really matter. <em>The keys are the key.</em></p><p>Now let’s look at the second line in our while loop — here we have another conditional — only <em>this</em> time we’re not using .includes(). Instead, we’re checking the keys in our hash table against our current number to see if there is a key that is already double, or half of, our current number. If that key already exists, then we know that we’ve found a double!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/1*PzPSLeYUoPx1rc5FfCuvLQ.png" /></figure><p>To break it down more explicitly…</p><ol><li>Our first run through the while loop (with array[i] = 4) produces doubles = {4: ‘cats are so cool’}. It runs through the conditional without returning anything because doubles has only one key, 4, and does not include a key of 8 or 2.</li><li>The second run through the while loop (with array[i] = 5) adds a new key to doubles — {4: ‘cats are so cool’, 5: ‘cats are so cool’}. Again it passes through the conditional without matching a key.</li><li>Finally, our last run through produces doubles = {4: ‘cats are so cool’, 5: ‘cats are so cool’, 7: ‘cats are so cool’} and exits the conditional and the while loop without matching a key.</li><li>Because there was no positive case to break us out of the while loop, our function returns false!</li></ol><p>Notice anything?</p><p>We wrote a function that does what it needs to do <em>without using a nested loop!</em></p><p>The Big O notation for this version of our includesDouble function is just O(n) = 3. If we had an array of a million numbers, Big O would be O(n) = 1,000,000. Compare that with O(n²) = 1,000,000,000,000 (one trillion) and we’ve shaved off a huge chunk of our function’s run time!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/0*D0bPLFl1a_IlcPRk.gif" /><figcaption>Ahhh… isn’t life good?</figcaption></figure><p>As great as our new function is, it does pose some trade-offs — first of all, our second function is a little harder to understand than our first. If you’re concerned about readability (maybe you’ve got a bunch of newbie programmers on your staff, like me) and you know that n is never going to be astronomically long, you may prefer to stick with the first option. Also, notice that in the second function we also create a brand new variable (doubles = {}). This means that your computer now has to create and set aside a specific place in memory to store that new piece of data. If you’re worried about memory space, and you know that n will always be a reasonable length, again you may choose to go with option #1.</p><p>There’s definitely more than one way to skin a cat…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/450/0*L6xbxiASEkhXJ_9c.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c8915086518" width="1" height="1" alt=""><hr><p><a href="https://medium.com/quick-code/considering-optimization-and-time-complexity-with-js-algorithms-4c8915086518">Considering Optimization and Time Complexity with JS Algorithms</a> was originally published in <a href="https://medium.com/quick-code">Quick Code</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring Recursive Routes with React]]></title>
            <link>https://medium.com/@jennyjean8675309/exploring-recursive-routes-with-react-693a604c1e31?source=rss-760302d1b208------2</link>
            <guid isPermaLink="false">https://medium.com/p/693a604c1e31</guid>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Jennifer Ingram]]></dc:creator>
            <pubDate>Fri, 15 Feb 2019 19:16:17 GMT</pubDate>
            <atom:updated>2019-02-15T19:16:17.210Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve recently recovered from a big headache — my latest project required some nested routes. Basically, I had a big container that held some smaller containers, and each of those smaller containers held a bunch of items, each of which I wanted to see rendered on its own page. If this is confusing to you — yes, I agree.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/422/0*GXKbXKm2RaeS1BE7.gif" /></figure><p>My first attempts at routing, linking, and redirecting to these nested urls were pretty messy. I was getting some weird url params as I clicked through my app that were making it difficult to get anything in my app working properly. So, I decided I should revisit this topic to gain a better understanding. I made a brand-spanking-new React app with only one goal in mind — conquering recursive routes. Here’s what I’ve discovered…</p><p><strong>The missing link — the secret key — the thing that makes it all come together</strong></p><p><em>The key to understanding nested params is React’s &lt;Route /&gt; component. </em>Any render method that you pass to &lt;Route /&gt; has the same three props:</p><ul><li>match</li><li>location</li><li>and history</li></ul><p><em>Match</em> is what we really care about.</p><p><strong>Have a plan</strong></p><p>Your routes should live at the top-most tier of your application, which for me, was App.js. I needed to import a few things at the top of my Index.js file to get this working…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*4eLSWdEH_nX0Bxf1.png" /></figure><p>Notice that my &lt;App /&gt; component is wrapped in a &lt;Router&gt;&lt;/Router&gt; component… now I can set up my initial routes in App.js. First, I want to add</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/481/0*vaYLyFIVAtT0Z2Gk.png" /></figure><p>to the top of my file.</p><p>My app will use some nested data to render specific information at specific urls. Here’s what my data looks like…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*wH5Sd_FYZS0qhetg.png" /></figure><p>This is right at the top of my App.js file, where I have access to it and can pass it down as props to all of my child components. My goal is to have a home page that has a link to the three rooms in my home (the kitchen, living room, and bedroom). When I click on any of those room links, my url will change (”/:id”) and I’ll see rendered on the page that particular room, with a list of furniture that that room contains. Each piece of furniture will be another link to that piece’s show page (”/:id/:f_id). Sounds easy enough, right?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*Ehuzlorv28Br8wlX.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*PZkxQtxRSQSD59-7.png" /></figure><p>Because I have a pretty good idea of what I want to render, and where, I’ll go ahead and set up my routes. Notice that within each &lt;Route/&gt;’s render method I’m passing in props — <strong>remember that the match prop is the key to making this whole thing come together.</strong></p><p>Before we move on, let’s take a quick second to see what that magical match props is…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/428/0*UQEzRZ-d_XvQdnNT.png" /></figure><p>Aha! The match prop has a key, params, that shows some pretty good stuff — including my current url. Interesting, interesting…</p><p>Let’s start with our outermost component first… our Home page.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*GKV5Uljvrwdx8fCL.png" /></figure><p>On my Home page I simply want to iterate through my rooms (this.props.rooms.map) and render each room on the page, using a &lt;Room/&gt; component. Notice that I’m passing through the props (from the App.js file) down to the &lt;Room/&gt; component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*5EIqLswqjD2MOrOd.png" /></figure><p>Now this is where those match props really come in handy!!! Each room’s name is now a link. React’s &lt;Link/&gt; component needs a path (to link <em>to </em>of course) and we can tack our current room info (this.props.room.id) onto the end of our previous url (this.props.match.url) to create our first <strong>nested route</strong>. Yes!!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/200/0*dFzlm-zGNiBszRbE.gif" /></figure><p>Uh-oh. But now if we check the routes we set in app, the route for “/:id” is expecting to render a &lt;RoomShow/&gt; component, which we haven’t yet made.</p><p>So… let’s make it!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*TDC1eTJ9kdi0-P2I.png" /></figure><p>Now things are getting a little bit tricky, but it’s nothing that we can’t handle — to find the current room that we’re in we’ll iterate through this.props.rooms to find the room that matches our current url (this.props.match.params.id). Then, we can use that information to render our current room, and iterate through that room’s furniture to create a list.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*-u3ao450atTbCeWk.png" /></figure><p>Here, we see that each piece of furniture is rendered as a link, and again, we’re using this.props.match to create a path for our link. Cool.</p><p>Checking our routes again, we see that our final route (”/:id/:f_id”) is expecting a &lt;FurnitureShow /&gt; component to render.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*iasWiFmALS6jDRsp.png" /></figure><p>Our furniture show page is now rendering the name of our piece of furniture… it’s working!!!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*IOZl72tj0GgFWTiS.gif" /></figure><p>Now sit back, click away, and bask in the glory of your success.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=693a604c1e31" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[UI Design Basics for Web Applications]]></title>
            <link>https://medium.com/@jennyjean8675309/ui-design-basics-for-web-applications-adaabc65cc4f?source=rss-760302d1b208------2</link>
            <guid isPermaLink="false">https://medium.com/p/adaabc65cc4f</guid>
            <category><![CDATA[web-design]]></category>
            <category><![CDATA[ui-design]]></category>
            <category><![CDATA[ux-design]]></category>
            <dc:creator><![CDATA[Jennifer Ingram]]></dc:creator>
            <pubDate>Fri, 15 Feb 2019 18:59:19 GMT</pubDate>
            <atom:updated>2019-02-15T18:59:19.447Z</atom:updated>
            <content:encoded><![CDATA[<p>A few months ago my sixteen year-old was taking an online course for Driver’s Ed (Yikes! — I know). The last lesson included a link to take the final test to earn her certificate for the course. We clicked on that link, which took us to another page with instructions to click on <em>another</em> link to find the final test. Well, <em>that </em>link took us right back to the <em>original page</em> we had started from! We were stuck in an endless link-loop with no final destination. Welcome to the Twilight Zone — online.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*IHkWRg-gCPU6jHJU.gif" /></figure><p>A lot of head-scratching, frustration, and several phone calls later, we were finally able to figure out what she needed to do and move forward.</p><p>The (true) story above is an illustration of poor user interface — the website was confusing, and we weren’t able to get the (rather critical) piece of information that we needed. Now, after a couple months of coding bootcamp, and with a few projects under my belt, the importance of good UI (or User Interface) design has been made even more clear. And good UI takes some planning.</p><p>Before we dive too deeply into how to implement good UI design, let’s talk a bit about what UI design is.</p><p>UI design (if done properly) tries to see things from a user’s perspective. Today’s world is chock full of some pretty savvy Internet users. They’ve been around, and they will come to your website with some expectations. As developers, it’s our job to make sure that we at least meet (if not exceed) those expectations.</p><p>As a developer, you want to ask yourself three basic questions about your application:</p><ul><li>Is it easy to access?</li><li>Is it easy to understand?</li><li>Is it easy to use?</li></ul><p>Here are a few examples of some sites that don’t quite pass muster…</p><p><strong>Argen</strong> — <a href="http://www.arngren.net/">http://www.arngren.net/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*PEOusuHB2C8tYxTK.png" /></figure><p>Whoa!!! Holy visual overload, Batman!</p><p>The designers of this site did make <em>some</em> attempt at organization — at least some of the boxes have borders around them. But if we’re being honest, there is no focus to this site! Links are just splashed everywhere and it looks like everything just got pushed and shoved onto the page in an attempt to fit as much as possible.</p><p><strong>University of Advancing Technology</strong> —<a href="https://www.uat.edu/"> https://www.uat.edu/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*3PjrOa9RJHHMGNjj.png" /></figure><p>Now this one’s pretty fun. See all those boxes around that guys head? Those boxes are all links to the programs that this university offers — and they continually spin around his head! It’s kind of like a game — is the program you want offered? — you might have to watch and wait for it to come around, and catch it when it flies by! This is great for a little distraction, but not so much for users who are serious about finding their program. There is no static list that you can quickly scan to see what you want. Though the flying, rotating boxes feature is cool, this just isn’t the most appropriate way to use it.</p><p>And, last but not least, we have:</p><p><strong>Serene Naturist</strong> —<a href="http://www.serene-naturist.com/"> http://www.serene-naturist.com/</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*F9teG3l4JYOyVLrZ.png" /></figure><p>This site is… not so serene. You can’t see it from this still screenshot, but if you click on the link above, allow flash player, and hit the play button on all of the myriad flash boxes, you’ll see about a <em>gajillion </em>different features bubbling, sparkling, fluttering, scrolling and/or blinking. And if those don’t make your experience more tranquil, there’s also a clock continually displaying the time (in seconds) at the top of the page (maybe to remind you that you’re always one second closer to death so you’d better take the time to relax?). It always helps to keep your target audience in mind, and have the atmosphere of your site reflect the atmosphere you want your company to have.</p><p>Having called out these sites, I need to offer a caveat — good UI design is <em>hard</em>. It’s easy to point out others’ mistakes, but when you go to build an application yourself, it’s even easier to forget the user’s perspective and throw things into your site all willy-nilly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/400/0*OmzEBm4-SpaDvJEl.jpg" /></figure><p>So, how do we, as developers, go about our UI design?</p><p>First, <em>plan before you build</em>.</p><p>Second, <strong>plan before you build</strong>.</p><p>Third, <strong>PLAN BEFORE YOU BUILD</strong>.</p><p>Okay, plan before we build — plan what?</p><h3><strong>Design</strong></h3><p>Plan out your design, starting with the <strong>functional requirements</strong> of your application first. Ask yourself, what are the goals of my application? What do I want this app to achieve?</p><p>After you’ve gotten a solid grasp on the goals of your app, do some <strong>user analysis</strong>. Try to imagine different user scenarios, thinking about the variety of users that might visit your site. What would those users need in order to use it? What might those users expect?</p><p>Next, plan out the <strong>logical design</strong> of your application. How does information flow through your site? What processes are used to implement that information flow?</p><p>From logical design, you can then jump to <strong>physical design</strong> — how will your logical design be implemented on a visual platform? How is information rendered on your page(s)?</p><p>*Note that the Design phase is purely <em>planning</em> — we haven’t started building out anything yet!</p><h3><strong>Implement</strong></h3><p>I know you’re anxious to begin building, but we have one more step to go before we get our hands wet…</p><p>Make a <strong>prototype </strong>of your app. Create a mockup (either on paper or using some online service) where your <em>sole focus is the interface</em> (now is not the time to add any potentially distracting pieces).</p><p>And now, drumroll please…</p><p>You can build.</p><p><strong>Construct</strong> your application (but remember to be flexible).</p><p>But we’re not done yet…</p><h3><strong>Testing</strong></h3><p>Test, test, and test again. Test your application with as many users as you can find, and have them throw as many different scenarios at you as possible. Challenge them to break your app, find a bug, or discover an endless link-loop.</p><p>Before I go, I want to leave you with a quick list of best practices to consider when (first!) planning and (then) creating your user interface design:</p><ul><li>Keep it simple — this doesn’t mean that you can’t showcase some great new feature or have fun — just make sure that you don’t overwhelm your user.</li><li>Be consistent and predictable — this will ensure that your users’ expectations are met and that they aren’t surprised (and turned off) by weird quirks.</li><li>Pay attention to layout, color and texture — aesthetics are important, ‘nuff said.</li><li>Use typography to express hierarchy and clarity — if your user can’t figure out what is most important on your site, they’ll have difficulty navigating it — lend ’em a hand.</li><li>Communicate with your user — if they submitted a form successfully, let ’em know! If they hit some error message, let ’em know why, and how they might fix it. Let them know too where they’re at in your site, and how they might get around.</li></ul><p>If you keep these simple ideas in mind, hopefully you can avoid this kind of response when others visit your site…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*SpKzvX0ZoIFLOUBC.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=adaabc65cc4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Keeping it Clean — Data Validation with Ruby on Rails]]></title>
            <link>https://medium.com/@jennyjean8675309/keeping-it-clean-data-validation-with-ruby-on-rails-a0c6190f1b8e?source=rss-760302d1b208------2</link>
            <guid isPermaLink="false">https://medium.com/p/a0c6190f1b8e</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[validation]]></category>
            <dc:creator><![CDATA[Jennifer Ingram]]></dc:creator>
            <pubDate>Fri, 15 Feb 2019 18:42:25 GMT</pubDate>
            <atom:updated>2019-02-15T18:42:25.933Z</atom:updated>
            <content:encoded><![CDATA[<h3>Keeping it Clean — Data Validation with Ruby on Rails</h3><p>Validation is super important. As my poor husband knows all too well, I often crave it. Who doesn’t need some affirmation every once in a while that they’re doing okay, that their thoughts and feelings are valid and worthwhile? My own personal neediness aside however, validation, when it comes to computer programming, can be <em>critical</em>.</p><p>As users of the Internet, we’ve all encountered a multitude of forms and fields that we have to fill out online — when creating a new blogging account, when completing a contact form for our children’s school, or even just typing something into a search field. How many times has your information gotten kicked back because of an error? My name is Jenny — it’s a pretty great name and it fits me real well — but there are also a bajillion other Jennys floating around the world. Every time I’ve tried to just create a simple username, ‘Jenny’, it’s gotten kicked back because some other Jenny has already beaten me to the punch and snagged up that username. As annoying as it is, validation for uniqueness of a username is really important — although I would love the coveted, clean, simple username of just plain ol’ ‘Jenny’ — I’m really glad that my username is unique. It makes it that much harder for someone to accidentally (or nefariously) get into my account. On the developer side, keeping the data clean makes it that much easier to manage.</p><p>So how does validation happen in the world of program development? How is it set up and at what point in a user’s experience and on the developer end do those checks for errors happen? Well, funny you should ask — because I’m going to cover all that (and more!) in this post — and guess what? — Rails makes it super easy.</p><p>To start, let’s give our users the ability to create something super important — something that might require a lot of checks so that we can be sure that the information we get back is clean and will fit nicely into our database. How about…</p><p>Smurfs!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*mZ4ENUK_BZUSKwg8.jpg" /></figure><p>Smurfs are perfect — they’re a little cultish, so they require a lot of checks before they allow you to join the village — your name must be smurfy (i.e. have “smurf” somewhere in it), you have to be at least 100 years old (but not older than Papa Smurf — ’cause he doesn’t want his wisdom challenged), and your color MUST be blue — no exceptions. Oh, and we also don’t want any two Smurfs to have the same occupation — any form of competition might disrupt this otherwise peaceful community.</p><p>Active Record comes with a nice set of Validation Helpers that perform some fairly common checks, including (but not limited to!):</p><ul><li>acceptance — for all of those checkboxes we click that ask if we ‘agree to the terms and conditions’</li><li>confirmation — when you need to check that two fields are exactly the same (i.e. when you create a new password)</li><li>format — when you need data entered in a specific way (i.e. MM/DD/YYYY for a birthdate)</li><li>exclusion/inclusion — when you want to be sure that certain values are excluded or included for an attribute</li><li>length — when you want your user to create a password with X number of characters or a tweet that can’t be over 140 characters long</li><li>numericality — checks that the info entered into a field is a number (this one comes with a number of sub-helpers that we’ll use in a moment)</li><li>presence/absence — checks that the user enters info/doesn’t enter info into a field</li><li>uniqueness — just what it sounds like — makes sure that the user entered info that is unique (i.e. not already existing in your database)</li></ul><p>Here’s some more information on <a href="https://t.umblr.com/redirect?z=https%3A%2F%2Fguides.rubyonrails.org%2Factive_record_validations.html&amp;t=MDFjM2E1YzhjNGFmN2E4MTk0MWRhOTUyMzdmMmJmYjU5YTk5MGZjNCxFeWpBR253TA%3D%3D&amp;b=t%3Aj3jjox04haGzAtn6xxD7kQ&amp;p=https%3A%2F%2Fjennyjean8675309.tumblr.com%2Fpost%2F180147710425%2Fkeeping-it-clean-data-validation-with-ruby-on&amp;m=1">Rails Validation Helpers</a>.</p><p>Let’s see how some of these work…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/0*XIcq2QxkyKcYjUDK.png" /></figure><p>Here you can see that I’ve created a simple form that our user can fill out to create a new Smurf.</p><p>*** Just a side note — if you’re familiar at all with Rails, you know that it uses some naming conventions when it comes to naming folders, files, paths, etc. I used the Rails Resource Generator for this project, using the word ‘Smurf’ — and Rails thinks that the plural of Smurf is Smurves (see the url above). Eh, at least it tries. We’ll just go with it. ***</p><p>Now we’ll navigate over to our Smurf model, and implement an easy validation (checking to see that a Smurf’s color is blue), using the #validates method…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*JoRwVpcTfx4jFZxL.png" /></figure><p>Here I’ve used the #validates method, calling it on the Smurf attribute that I want to check, :color, and then the helper that I want to use, inclusion. The inclusion helper takes in an option in:, that accepts any values that you want to allow the user to enter for that particular attribute — because we only allow our Smurfs to be blue, I’ve given it just one option, blue. (If we were to allow more, we’d simply separate them with a single space (no commas).</p><p>Now let’s pop over to our ‘Smurves’ Controller (thanks for the help, Rails) to see how we implement this validation with the user input.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/485/0*K7STSJhCasmQv0vb.png" /></figure><p>Note that, at the beginning of my create action I’m using the params from the form (as strong params, defined below) to make a new Smurf <em>instance</em>, using the #new method, <strong><em>not</em></strong> #create. This is very important! Using #new will make a new instance <em>without</em> saving it to my database. Remember, we want to validate our user input <em>before</em> it gets saved to the database — because once it’s in our database, that’s where we might run into problems later on. So, before we save our new Smurf to our database, we want to check its validity first, using the #valid? method. This method is tied to the #validates method we defined in our Smurf model. If our Smurf is invalid (i.e. not blue) it won’t save to our database, but instead the user will be shown the edit form again.</p><p>Let’s see how this works…</p><p>Here’s my form, and, as you can see… I’m trying to create an invalid Smurf with the color green.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/314/0*0eQu2Xm7Fn0dLeVO.png" /></figure><p>What happens when I click the button to ‘Create Smurf’ is that my validation checks the user input for validity and kicks me right back to my edit form. Cool, but not cool… how would a user even know what went wrong — they might just assume that my application is broken and move on to <a href="https://procatinator.com/">procatinator.com</a> or something more fun. There is one place we can check though to see what’s going on under the hood, let’s inspect our web page’s html response…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*iPPgyuhBpzPYWtlr.png" /></figure><p>Rails does something cool when our information is invalid… it creates a new division tag (&lt;div&gt;) in our HTML response with its own class — “field_with_errors”. This tells us that the user params came back with errors.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/250/0*xQVsHg6xhatF0xeL" /><figcaption>Sorry, little Smurf — ejected!</figcaption></figure><p>Okay, so now how do we tell our user what went wrong so that they can fix it?</p><p>Easy! Remember the HTML response I just showed you after we submitted a form with an error? We can now expect that error response from Rails and use it in our own code to display errors (and messages) to our user…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/479/0*D2j7gX7tZm5mWFNG.png" /></figure><p>The #errors method from Rails knows to look in our HTML response for any of those &lt;div&gt;s with a class of “field_with_errors”. Our code then counts those errors for us (using Rail’s handy pluralize method to differentiate between an error and errors) and then each error gets the #full_messages method called on it to display those messages (each validation helper comes with its own default message). Cool!</p><p>Now, when our user tries to create an invalid Smurf they see…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/0*2AXgu6DkkFQAG3dR.png" /></figure><p>Wow! Now that’s really helpful! Now our user knows why the form came back (there was an error) <em>and</em> our super helpful code tells them exactly <em>where</em> the error occurred (in the color field) and <em>why</em> (’All Smurfs must be blue’).</p><p>Woah, woah, woah… ‘All Smurfs must be blue’ <em>cannot</em> be a <em>default</em> error message from Rails — unless those Rails developers are havin’ a whole lot of fun. Where did that super specific and smurftastic error message come from? Remember, way back a long, long time ago when we did this…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/540/0*Wfw2iShhs5kl_pKp.png" /></figure><p>Oh yeah! There it is! We gave Rails a <em>custom error message</em> when we typed out our #validates method for inclusion! Smurfity Smurf! That’s so smurfin’ awesome!</p><p>Okay, now let’s implement our other validations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/0*GFuaD4OhfAhtMBoE.png" /></figure><p>Here I’ve added a validation for occupation, that checks to see if the user entered a unique occupation by setting uniqueness: to true. Let’s see if it works.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/491/0*SBwnCfN8OZ_fFP6q.png" /></figure><p>Uh oh! Looks I already have a Smurf who is an artist. I didn’t do any magic tricks behind the scenes here — because I already added the code to my form to show error messages, what’s displayed here is the <em>default</em> message for a uniqueness validation error. Now my user knows that the value entered into the occupation field has already been taken. Hmm… I guess Van Gogh Smurf could take up basket weaving or something.</p><p>Now let’s set up our validation for a Smurf’s name. Hmm… now this one’s a bit tricker — we can’t use the inclusion helper, because anything we enter as an allowable field would have to be one of those values, and <em>only </em>one of those values. For example, if we did</p><p>inclusion: { in: { %w(Smurf) }</p><p>this would only allow our user to be named “Smurf” and nothing else. As cultish as they are, we do want to allow some individuality in Smurf Village. Sounds like this is a good time for a <em>custom</em> <em>validation</em>.</p><p>Rails has a few different ways to set up custom validations, but I’m going to tackle what I think is the simplest solution here — using <em>custom methods</em>. Let’s go back to our Smurf model to implement this.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/455/0*7-msYBQ7fGFZhrBH.png" /></figure><p>Now you’ll see that I’ve added a couple of things to my Smurf model — let’s start by taking a look at the new method, #name_must_be_smurfified. Here, I want to check for a false case (i.e. an invalid name) so I’m checking to see that the name is <em>not </em>Smurfified through</p><p>name.include?(”Smurf”) == false</p><p>If the name doesn’t include “Smurf” then I want to add an error message for the particular attribute I’m checking for, and a custom message to go along with it.</p><p>Then, under my other validations, I use the <em>#validate</em> method (in Rails a validation helper uses #validates, whereas a custom validation uses #validate (no ‘s’), calling it on the method I just defined, ‘name_must_be_smurfified’.</p><p>Let’s see if it works!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/502/0*PcAPBjbH_WP-dgzD.png" /></figure><p>Ugh, Harold! It’s like you’re not even trying! Do you want to be a Smurf or don’t you!?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*plwO-HLK_gCEtn9-.gif" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/386/0*xKpkZWj_K6msNKW0.png" /></figure><p>Smurf me blue all over! Harold came through, Smurfified his name, and now we can see that our validation method worked, it saved Harold Smurf as a new Smurf, and redirected our user to the Smurf’s show page! Yes!</p><p>And, if we take a peek at our Smurf Villagers, we’ll see he’s been added:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/458/0*EzOWQw6pECRMLrrn.png" /></figure><p>Yes! There is he is! He’s saved to our database and we can rest easy knowing that Smurf Village is neat and tidy.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*ojsz8MySw1tJhI4L.gif" /></figure><p>One more validation to go!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/451/0*58kGvm25CBx0xXAj.png" /></figure><p>Here, you’ll notice that I’ve switched things up a bit — using <a href="https://t.umblr.com/redirect?z=https%3A%2F%2Fapidock.com%2Frails%2FActiveModel%2FValidations%2FHelperMethods%2Fvalidates_inclusion_of&amp;t=YTU4NjA1MDAxYmQxYzBjNmU5ZTk2NjUxYzg3YjQ0NDIxOGZiZTliYSxFeWpBR253TA%3D%3D&amp;b=t%3Aj3jjox04haGzAtn6xxD7kQ&amp;p=https%3A%2F%2Fjennyjean8675309.tumblr.com%2Fpost%2F180147710425%2Fkeeping-it-clean-data-validation-with-ruby-on&amp;m=1">#validates_inclusion_of</a> with a little bit different syntax. I want to validate the age attribute, making sure that the new Smurf’s age is somewhere between the range of 100 to 541 (Papa Smurf is 542 years old — I know, right!?), and I made another custom error message.</p><p>How do these two methods compare? Is one better than the other? Is one older than the other? The answer is… I don’t know! What I <em>do</em> know is that they both worked — so I may continue playing around with the syntax and continue checking that they work until I find out what my preferences are.</p><p>So, let’s check one final time to be sure that our validations are all working…</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/508/0*257dsFEM72nINlOm.png" /></figure><p>Awesome! Our system is working <em>and</em> our user knows how to re-submit the form correctly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/387/0*Gc-KQGsyfd-yjp0O.png" /></figure><p>Smurf-a-rific! Now we’ll be sitting on database gold!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/0*6zP5aPsy0hixT2rf.gif" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a0c6190f1b8e" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>