<?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 Matthew Bates on Medium]]></title>
        <description><![CDATA[Stories by Matthew Bates on Medium]]></description>
        <link>https://medium.com/@matthewhcbates?source=rss-32ec8b880104------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*DqQxSdn8PJgaiEavJ1uSXQ.png</url>
            <title>Stories by Matthew Bates on Medium</title>
            <link>https://medium.com/@matthewhcbates?source=rss-32ec8b880104------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 12:50:26 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@matthewhcbates/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[Google Authentication Using React & Firebase]]></title>
            <link>https://medium.com/@matthewhcbates/google-authentication-using-react-firebase-e23d00d10efa?source=rss-32ec8b880104------2</link>
            <guid isPermaLink="false">https://medium.com/p/e23d00d10efa</guid>
            <dc:creator><![CDATA[Matthew Bates]]></dc:creator>
            <pubDate>Fri, 03 Mar 2023 22:19:47 GMT</pubDate>
            <atom:updated>2023-03-03T22:19:47.650Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*zoQMWN8sQRtRlOl8.gif" /></figure><p>It’s no secret that adding login authentication to your application can be a daunting task, especially when you’re generating it from scratch. Don’t get me wrong: it’s important to understand how authorization works as a whole, but if you’re not a truly seasoned developer, your code:</p><ul><li>Can become prone to security issues</li><li>Will become complex and time-consuming to build</li><li>etcetera, etcetera</li></ul><p>Firebase is a Backend-as-a-Service (BaaS) built on Google’s infrastructure. One key feature Firebase provides is authentication, which can help abstract a lot of the more difficult aspects of generating, for instance, it on your own. By the end of this article, my hope is for you to be able to incorporate Firebase authentication (as needed, of course) in your next project!</p><p><em>Disclaimer</em>: I’ll be creating a several components and utilizing routes using <a href="https://reactrouter.com/en/main">React Router</a>. I’ll also be generating some styling using <a href="https://sass-lang.com/">Sass</a>. My hope is you have a basic understanding of both React and the react-router-dom node package.</p><h4>Getting Started</h4><p>Let’s go ahead and generate a new React application:</p><pre>npx create-react-app google-authentication</pre><p>As I mentioned above, we’ll be using the react-router-dom/sass node packages to handle routing between the &lt;Home /&gt; and &lt;SignIn /&gt; components inside of the &lt;Navbar /&gt; component, so in your root directory, go ahead and install these react-router-dom dependency:</p><pre>npm i --save react-router-dom<br>npm i --save sass</pre><p>Since the primary focus of this article is Google authentication with Firebase, I want to keep things as simple as possible with regards to styling and functionality. That being said, we are ready to write some code!</p><h4>Generating A Quick &lt;Navbar /&gt; Component</h4><p>Inside the src folder, create a components folder and a subsequent Navbar folder, where you’ll generate two files: an index.js file and a NavbarElements.scss file (the former will be our component and the latter will be our Sass file). Use this code inside the NavbarElements.scss file:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/688/1*FSohqGGitnprHbym39SKPg.png" /></figure><p>Feel free to style this however you please — this is just a basic example. Back inside the index.js file, import the along with Link and Outlet from react-router-dom. Outlet isn’t necessary, but I like to include it to ensure a particular component will render on every page regardless of route change. We’ll have two Links, one for the home page (“/”) and one for the signin page (“/signin”). Your file will look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1006/1*LREjyjA-62cvq-UkbJxKYg.png" /></figure><p>Navigate to App.js, clear out the auto-generated code from when the React application was created, and replace it with the &lt;Navbar /&gt; component. From here, we’ll need to import Routes and Route from react-router-dom at the top of the file:</p><pre>import { Routes, Route } from &quot;react-router-dom&quot;</pre><p>Wrap the &lt;Navbar /&gt; component Real quick, just for styling sake, go to the index.css file and add the following CSS:</p><pre>* {<br>text-decoration: none;<br>}</pre><p>If you run npm start, you should see this in the browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*serS4E2VI50hzsRlhVuUcg.png" /></figure><p>Easy enough, right? Let’s move on to the good part — setting up our Firebase authentication!</p><h4>Creating A New Firebase Project</h4><p>Navigate to the <a href="https://console.firebase.google.com/">Firebase</a> homepage and in the top-right corner you’ll see a link titled, “Go to console” — click on that. This is the page where you can generate a new Firebase project, so click the + and title project accordingly — I named mine, “google-auth-demonstration.” Accept the terms and conditions, hit the, “Create project” button and we are well on our way to implementing Firebase authentication in our project!</p><p>You’ll be redirected to your projects homepage where we’ll first need to actually add Firebase to our application, so let’s get started on that. On the center of the page, you’ll see the text, “Get started by adding Firebase to your app” — click on that, create a nickname (I used the same as my project title, “google-auth-demonstration”). We can forego checking the box to set up Firebase hosting as it doesn’t apply to our application. Click on the, “Register app” button and what you’ll see are three to-do’s: a prompt to install the Firebase node package, two imports add to our firebase.js file we’ll create shortly, and an object for Firebase configuration. Let’s hop back over to our React project and in the root directory, install the Firebase node package:</p><pre>npm i --save firebase</pre><p>Create a utils folder inside src, and add a file named firebase.js. This is where we’ll initialize the code necessary to implement Google authentication.</p><h4>Firebase Configuration</h4><p>This will be the trickiest portion of the setup process, but I’ll break it down to where it should make plenty of sense. First, we’ll need to import initializeApp at the top of the file, as stated on the Firebase setup instructions:</p><pre>import { initializeApp } from &quot;firebase/app&quot;;</pre><p>This will create our app instance and is absolutely necessary to proceed. From here, we’ll need to add the firebaseConfig object to our file. You might be thinking, “shouldn’t we create a .env to hide these keys?” and the short answer is no: the configuration snippet just identifies your Firebase project on the Google servers and it’s not a security risk if someone knows it. To initialize Firebase, add the constant that’s provided on the instructions:</p><pre>const app = initializeApp(firebaseConfig);</pre><p>You can rename this variable to, say, firebaseApp, but it really doesn’t matter.</p><p>We’ll need to import a few functions from “firebase/auth”, so let’s get to that. At the top of the file, import the getAuth, signInWithPopup, and GoogleAuthProvider functions, like so:</p><pre>import { getAuth, signInWithPopup, GoogleAuthProvider } from &quot;firebase/auth&quot;;</pre><p>What do these functions do, you might ask? Great question! getAuth is the most important as it returns the auth instance associated with the provided Firebase application. signInWithPopup authenticates the Firebase client using a popup-based OAuth authentication flow. Lastly, GoogleAuthProvider generates an OAuthCredential for ProviderId.GOOGLE.</p><p>A couple more steps and we’re done! To sign in using a redirect, we’ll create a new instance of GoogleAuthProvider to generate an OAuth credential:</p><pre>const provider = new GoogleAuthProvider();<br>provider.setCustomParameters({<br>  prompt: &quot;select_account&quot;,<br>});</pre><p>To break it down:</p><ul><li>We are assigning the constant named provider to a new GoogleAuthProvider instance</li><li>We then set the OAuth custom parameters to pass in an OAuth request for popup and redirect to Google login</li><li>Lastly, “select_account” simply asks Google to show the account selection page every time you login (You experience this when you log in with your Google account and are asked which account you’d like to log in with — useful when you have more than one account)</li></ul><p>We’ll add two more lines of code to wrap up the authentication portion:</p><pre>export const auth = getAuth();<br>export const signInWithGooglePopup = () =&gt; signInWithPopup(auth, provider);</pre><p>We are exporting/invoking our auth instance associated with our Firebase project and creating an additional variable that returns a promise with our user credentials (authorizing your particular account and the provider it’s associated with). Your code should look very similar to this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*u48Bl1XTXcFc8TFG8fLm1A.png" /></figure><p>Head back to the browser and on the project homepage, click on the Build dropdown and subsequently select Authentication. We’re using Google, so click on the Google button under Additional providers. Toggle the enable button, provide a project support email (I used my Gmail account, but it can be anything), and hit save. No need to worry about client ID’s or Web SDK configuration for now. If you see a status of enabled, you’re all set!</p><h4>Adding The &lt;Home /&gt; And &lt;SignIn /&gt; Components</h4><p>Head back to React and create two additional folders in the components folder: Home and SignIn. These need only be very simple in nature, for the Home component, it should look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/904/1*RJUslSW0ccBwThehHWObPg.png" /></figure><p>Next, create your SignIn component, which will look something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*_y2tI-V1TSO5QADL4TZ-Cg.png" /></figure><p>The functionality is very simple here: we’re importing the signInWithGooglePopup we exported in firebase.js, creating an asynchronous function (per standard practice), and assigning the constant response to the invoked function that takes the auth/provider as arguments.</p><p>Add a click event to the button, pass in the function we just created, and import these two new components to App.js. Recall when we imported Routes and Route from react-router-dom? We’ll now put those to good use. Since we used &lt;Output /&gt; in the Navbar component, this will display regardless of route change. Home and SignIn will be children routes to their parent, Navbar. The code looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9rdn4Kx9smiVH-0wuuGQEQ.png" /></figure><p>And guess what — we are done! No thanks to our extremely bland styling, our Google authentication button should now be fully functional, so let’s check it out. Go to the browser (run npm start if you haven’t already), and click on the button. You should be redirected to log in with your Google credentials:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/703/1*ZMi8f5uckFBWBMSJQTUi_A.png" /></figure><p>Would you look at that, it works! If you’re wondering what that wonky “.com” refers to, it’s simply pointing to your Firebase project (you can go back to the main project page to verify this).</p><h4>What’s Happening Behind The Scenes?</h4><p>In a nutshell, what’s happening is our application is requesting sign in credentials from the Google server (in my case, my Gmail account), which will respond with an auth token if there’s a match. Our application then sends this auth token to Firebase and Firebase will subsequently check with Google to ensure that it is, in fact, a legitimate token. If it is, Google then sends Firebase a verification token which is finally sent to our application. From there, our application is granted an access token where can make, for instance, CRUD requests to the Firebase database. This is a very dumbed-down description of what’s happening, and doesn’t take into account error handling (which I didn’t cover for the sake of time).</p><h4>Wrapping Up</h4><p>Firebase authentication is a very useful way to expedite authentication for your applications without having to worry about creating it from scratch (and not to mention, the security risks it might pose). There is so much more Firebase can do for you and your applications, but I believe authentication is one of the most useful tools they provide.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e23d00d10efa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Algorithms & Time Complexity]]></title>
            <link>https://medium.com/@matthewhcbates/algorithms-time-complexity-1f36441a3cd7?source=rss-32ec8b880104------2</link>
            <guid isPermaLink="false">https://medium.com/p/1f36441a3cd7</guid>
            <dc:creator><![CDATA[Matthew Bates]]></dc:creator>
            <pubDate>Thu, 28 Apr 2022 20:28:14 GMT</pubDate>
            <atom:updated>2022-04-28T20:28:14.436Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*boTVQzqGyaQpvSI7.gif" /><figcaption>GIF courtesy of <a href="http://www.tenor.com/">Tenor</a></figcaption></figure><p>I’ve been an enormous <a href="https://www.codewars.com/dashboard">Codewars</a> enthusiast as of late. Being a relatively new software developer, their platform is incredibly user-friendly, allowing me to test my mettle in a variety of languages/difficulties. One of my favorite features: after successfully solving a <em>Kata </em>(a code challenge) with a working algorithm, you’re able to refactor your code &amp; compare it to others. It’s been such a confidence boost, &amp; extremely rewarding to boot, for each <em>Kata</em> I find a solution for. As I prepare for technical interviews, I keep circling back to a topic I barely scratched the surface on: Big O notation.</p><h4>What Is Big O Notation?</h4><p>Big O notation is commonly referred to by many, if not all, software engineers &amp; developers. Even more so, the importance of the knowledge behind this theory becomes significantly bigger as you encounter larger &amp; larger databases. Its primary use is to communicate how fast an algorithm can compute. In regards to runtimes, the five most encountered are as follows (fastest to slowest):</p><ul><li>O(log<em> n</em>); O(1): a.k.a. “log time”</li><li>O(<em>n</em>): a.k.a “linear time”</li><li>O(<em>n</em> * log <em>n</em>): a fast-sorting algorithm</li><li>O(<em>n</em>²): a slow-sorting algorithm</li><li>O(<em>n</em>!) a <em>very</em> slow-sorting algorithm</li></ul><p>The purpose of this article is not to do a deep-dive into theory, rather, to demonstrate how I’ve been taking runtime — time complexity — into account for Codewars problems; I’m also negating focus on space complexity.</p><h4>The Kata</h4><p>Codewar <em>Kata</em> are sorted via <em>Kyu</em>, which indicates the number of degrees away from master level, <em>Dan</em>. Being a 8<em>Kyu</em>, the <em>Kata</em> in question is on the relatively easy side, but will demonstrate Big O quite well. So, here it is:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/655/1*IiXfV_MwHF0xr7v7Yrbwng.png" /></figure><p>The test cases were as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/457/1*mt-iiTugFPn6WNReRuNDTg.png" /></figure><p>The only argument provided, <em>num</em>, could be any number of integers; all that matters, however, are positive integers. I decided to declare one variable set to an empty string that would accumulate the count of <em>num</em> as it was iterated upon, starting the count @ 1. The resulting count was subsequently converted to a string &amp; added to string text <em>“ … sheep” — result</em> was then returned. The code ended up looking like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*V1SfzK6twn0miNvLLTVVbg.png" /></figure><p>Lo and behold, the tests passed. Having digressed a bit, let’s get back to how this ties into Big O notation by running a sample <em>num </em>utilizing <em>performance.now() </em>method. The returned value will represent time elapsed between the interpolated difference of time2 less time1, while invoking <em>function countSheep() </em>in between. Using Chrome DevTools’ snippet feature, I’ll insert this method &amp; log the time elapsed, with an input of 1,000:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/426/1*nwAa_eNd7vzGvRFhoBPbkQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/330/1*ST7IxeShw3d5rEsmVgfR-w.png" /></figure><p>The time elapsed is <em>incredibly </em>short, albeit having slightly deviated runtimes. But, what would happen if I drastically increased the input, say, to 10,000,000 (hoping it doesn’t crash the browser)?:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*ZnJNEyWC3SUYA4aS-6FPvg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/586/1*791D3szxKj59pmr7ukpPtQ.png" /></figure><p>In comparison to an input of 1,000 there was a <em>massive</em> difference in runtime!</p><h4>Another Example — How Will Runtime Compare?</h4><p>Upon submission, you’re able to look at all the different ways other users solved the problem. For example, using the reduce method, the function could be written as such:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/339/1*ThJYUC9OcbGUdeeW3G4W1A.png" /></figure><p>I’ll go ahead and run both versions of the function three times, logging the output for comparison:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*T6Dy5IGL0tEtdwcI6-29kw.png" /><figcaption>My Solution.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/589/1*JqDAXY67YEmE_MR6RFyrNQ.png" /><figcaption>Reduce Solution.</figcaption></figure><p>There’s nearly a <em>two second</em> difference in runtime, so how can this be explained?</p><h4>Methods &amp; Counting Operations</h4><p>The runtime will always be determined by the number of simple operations the computer has to perform.</p><p>Let’s take a look at the reduce solution first &amp; refer back to Big O runtimes. One of the biggest selling points of arrays are that the are ordered, unlike objects — which can come at a cost. The array is iterated upon from index 0, up to <em>n</em>, despite size; each element is acted upon, in order. As the size of the array grows, so does the amount of time it takes — this can be classified as O(<em>n</em>), or linear time. If I were to run this function with one-billion instead of ten-million, you could expect the runtime to proportionately grow with the input.</p><p>Conversely, my solution comes with one advantage — the data is not stored in an array, so order doesn’t matter. My solution will still be classified as O(<em>n</em>), but let’s take a look at the following &amp; physically count the operators in my solution:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*MHpa4WgmWxcSy5M77k9bqQ.png" /></figure><p>Regardless of the exact number, the number of operations grows roughly in proportion of <em>num</em>.</p><h4>Wrapping Up</h4><p>In summation, different solutions can certainly have an impact on runtime in regards to Big O notation, <em>especially</em> as the input grows. If you happen to see any errors in this article, please reach out so I can correct it! As always, thank you for reading — I hope this was informative.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1f36441a3cd7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Adjusting To Life Post-Bootcamp]]></title>
            <link>https://medium.com/@matthewhcbates/adjusting-to-life-post-bootcamp-f19e6ab1ab7e?source=rss-32ec8b880104------2</link>
            <guid isPermaLink="false">https://medium.com/p/f19e6ab1ab7e</guid>
            <dc:creator><![CDATA[Matthew Bates]]></dc:creator>
            <pubDate>Tue, 12 Apr 2022 19:50:30 GMT</pubDate>
            <atom:updated>2022-04-12T19:50:30.555Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*tDYv9yXc-iGZsd-t.gif" /><figcaption>GIF courtesy of <a href="https://tenor.com/">Tenor</a></figcaption></figure><p>Well, I did it: I graduated from Flatiron Schools’ rigorous, 15-week software engineering program. What seemed like an impossible endeavor was eventually thwarted by my confidence levels steadily increasing. However, just like many of my fellow cohort members, I was left with asking myself, “what now?” Being so used to a curriculum that — day-in and day-out — left me completely drained, I’m now met with a number of new challenges, namely job acquisition. I want to talk about what my primary focuses are in for those who might be struggling to find balance, post-bootcamp.</p><h4>First &amp; Foremost — Update That CV!</h4><p>My first goal after graduation was converting my CV to be much more tech-focused. It was a challenge to integrate my previous accomplishments to incorporate my new set of skills; however, this is a CRUCIAL first step! Don’t you want to showcase your projects you worked so hard on, &amp; let potential employers know about your new skill stack? As far as your technical skills go, you can certainly list them all out separated by a pipeline ( “|” ) — that’s how mine looked for a long time. However, I found it to look much cleaner when I broke down my skillsets into their own categories, such as <em>Languages &amp; Frameworks, Source Control &amp; CI/CD, Data Markup</em>, etc. In regards to the projects I wanted to showcase: I found it absolutely necessary to include my GitHub links &amp; a live demo of the application as a whole, walking through all of the U.I. functionality. I used <a href="https://vimeo.com/">Vimeo</a> which was is incredibly user-friendly.</p><h4>Clean Up Your GitHub</h4><p>For the projects you’re listing on your CV, I recommend going through your GitHub README’s &amp; making those look as clean as possible. I used <a href="https://github.com/Ileriayo/markdown-badges">GitHub markdown badges</a> that allow you to link your social media accounts, as well as the languages/frameworks you used per project — take a look below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/806/1*7Kwif4jDDKPIlfXlTjn8sw.png" /></figure><p>I have several projects showcased on my profile page, some of which were phase-end projects for Flatiron — needless to say the README’s were a bit messy. Updating these files DOES make a difference!</p><p>Speaking of README’s, did you know you can create a profile page that gives a user immediate insight of your programming journey? I used this <a href="https://rahuldkjain.github.io/gh-profile-readme-generator/">pre-built README generator</a> that’s really easy to fill out, &amp; looks great to-boot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*Ndy-dsYHtRNEb7lTkkxYrA.png" /></figure><p>With minimal effort, you can make your GitHub look very professional!</p><h4>Dive Into Data Structures &amp; Algorithms</h4><p>When I first started my software engineering journey, there was nothing quite as daunting as DSA’s. Now that I have graduated, my time has been heavily focused on mastering some of the more basic algorithm’s and data structures. I have found that <a href="https://www.codewars.com/">Code Wars</a> is a GREAT resource for doing just that, and, in my opinion, is much more user-friendly for greenhorn programmers compared to Leet Code. You’re able to complete challenges on your own, or take turns practicing refactoring others’ code. Definitely worth checking out, in my opinion!</p><p>I’ve also purchased a book for what some consider to be the end-all, be-all for technical interview preparedness, <a href="https://www.amazon.com/Cracking-Coding-Interview-Programming-Questions/dp/0984782850"><em>Cracking the Coding Interview</em></a><em> </em>&amp; I cannot stress enough how much this book has helped me the past few weeks. Although my program left me with many repositories for practicing DSA’s, I have found these two outside resources to be pivotal as I progress as a software engineer.</p><h4>Wrapping Up</h4><p>Just because I have successfully completed my software engineering program does not mean my journey is over; on the contrary, it has just begun! I hope that you’re able to takeaway a few tidbits that have <em>certainly</em> helped me stand out as I have been applying to, what will hopefully be sooner rather than later, my first career as a software engineer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f19e6ab1ab7e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Google Maps API With React.js]]></title>
            <link>https://medium.com/@matthewhcbates/implementing-google-maps-api-with-react-js-99c4afb71e73?source=rss-32ec8b880104------2</link>
            <guid isPermaLink="false">https://medium.com/p/99c4afb71e73</guid>
            <dc:creator><![CDATA[Matthew Bates]]></dc:creator>
            <pubDate>Wed, 23 Mar 2022 19:39:42 GMT</pubDate>
            <atom:updated>2022-03-23T19:53:49.789Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*eVjKSkAbsfujCUTF.gif" /><figcaption>GIF courtesy of <a href="https://tenor.com/">Tenor</a></figcaption></figure><p>It seems quite abstract to think that I’m in the fifth &amp; final phase of my software engineering program at Flatiron School. I’m currently knee-deep in my Capstone project; I thought I would shift gears &amp; share my implementation of an API that has added a vast amount of value to both this endeavor, as well as my previous project.</p><p>Google — we all know this six-letter word very well. Whether it’s using their incredibly broad databases to search for practically any inquiry we have (and as software engineers, we do this quite often!), the world is literally at our fingertips. Take this one step further &amp; we have Google Maps, a navigation service that provides directions for millions of users worldwide. As I grow as a developer, I’m constantly pushing myself to see what I can inject into the apps I develop, &amp; the Google Maps API takes the cake for both the most frustrating/rewarding challenge to-date.</p><h4>The First Steps</h4><p>Before we can use Google Maps in our application, you’ll need to create a Google Map account which you can do <a href="https://developers.google.com/maps/gmp-get-started">here</a>. After you’re all set up, you’ll be rewarded with an API key &amp; a $200/month credit to your account. Don’t worry too much about what the credit is for — it basically correlates with a high volume of traffic to your application, if that turns out to be the case. Assuming that you already have your React app set up, navigate to the CLI and enter the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/632/1*W8PumSq7F8OFnPe5IbAA5g.png" /></figure><p>Believe it or not, that’s all you really need to do to get started! I’m currently making a hiking application for my Capstone, hence the route. Going forward, I’ll remain consistent with my current endeavors for this project.</p><h4>Rendering Google Maps To Your React Component</h4><p>Now for the fun part! I imported/routed my component inside <em>App.js </em>&amp; fetched my seed data pertaining to hike information:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/258/1*a-aGCQ0__uy1l85jt4PPYA.png" /><figcaption>I used Bootstrap for my &lt;Route(s)&gt; elements.</figcaption></figure><p>Having generated said <em>Trailheads.js</em> component, I set up my class function and imported <em>{ GoogleMap, Loadscript } from ‘@react-google-maps/api </em>which was carried out in my CLI earlier. The logic behind implementing maps took a bit of research, but ultimately it was not difficult to do most of it on my own.</p><ul><li>I set a variable to <em>defaultCenter </em>for Manitou Springs’ coordinates so on page load, I would zoom in on my location.</li><li>I set an additional variable to <em>mapStyles </em>that basically renders Google Maps to full screen</li></ul><p>Inside my component return, <em>&lt;Loadscript googleMapsApiKey=”YOUR_API_KEY” /&gt;</em> was replaced with my generated key I grabbed earlier. <strong>Aside: </strong>it’s definitely important to hide your API keys, especially if you have a public repository. Learn more about that <a href="https://geodoo.work/hide-secure-api-keys-created-app-create-react-app/">here</a>. All together, my class component looks like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/468/1*BLctAZDVELP1MO9wh9p8qA.png" /></figure><h4>Adding Clickable Map Markers</h4><p>What good would your Google Maps API be without some clickable P.O.I’s? It turns out that’s not incredibly difficult, with the help of some hard-coded locations (which you can choose to refactor down the road, if you wish). I created an array through my variable <em>locations </em>that holds a list of objects which include the names of my markers, as well as their latitude/longitude coordinates (this list will grow as my project grows):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/223/1*2yTvLDf29T7hpLtfBFPE8A.png" /></figure><p>I had to update my import to <em>{ GoogleMap, LoadScript, </em><strong><em>Marker</em></strong><em> } </em>as <em>Marker</em>. It wasn’t too difficult to realize that an iteration was necessary on my ever-growing list of objects. <em>GoogleMap</em> is a higher-order component so I included <em>.map</em> with an explicit return after the opening element, like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/244/1*LZx6D39ZnvP8PskMoNOVtQ.png" /></figure><p>With this in place, my markers populate wherever I include latitude &amp; longitude!</p><h4>Including Information Windows</h4><p>The last piece I wanted to cover was the ability to include information windows when a particular marker is clicked on. To do so, I updated my import once more to <em>{ GoogleMap, LoadScript, Marker, </em><strong><em>InfoWindow</em></strong><em> }</em> &amp; got to work. I ended up including a <em>&lt;Button&gt;</em> that routed the user to another page pertaining to that particular hike, with all sorts of information included. I won’t spoil that quite yet as I haven’t presented, but I’ll be following up with a subsequent blog about the project as a whole, after.</p><p>Digressing, to make this work, I added an <em>onSelect</em> method inside the <em>&lt;Markers /&gt;</em> component to show details pertaining to a particular hike. Additionally, inside my <em>&lt;InfoWindow /&gt;</em> component I added an <em>onCloseClick</em> method to “X” out of the info window. Lastly, I had to store the selected location in state:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/343/1*p3MhICWM0atOh5mBI9OSTA.png" /></figure><p>All together, my <em>&lt;Marker /&gt; &amp; &lt;InfoWindow /&gt;</em> components look like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/357/1*TzL1Qo0TVVPkz_UQI3GKfA.png" /></figure><p>And in my app, we have a fully functioning API!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/975/1*Kr-7hEfN0N5TIkiLvUH7jg.png" /></figure><p>There’s several other tidbits I included in my Google Maps API, but again, I want to save that for after I present my Capstone.</p><h4>Wrapping Up</h4><p>All-in-all, I am very pleased with how this turned out. Albeit banging my head against a wall several times throughout the process, I’m quite happy with the results. If you have any questions, please don’t hesitate to reach out (and if you like my content, click that “follow” button!).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=99c4afb71e73" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React.js & Ruby on Rails — End of Phase Project: Brewery Discovery]]></title>
            <link>https://medium.com/@matthewhcbates/react-js-ruby-on-rails-end-of-phase-project-brewery-discovery-12ad3dc1b90f?source=rss-32ec8b880104------2</link>
            <guid isPermaLink="false">https://medium.com/p/12ad3dc1b90f</guid>
            <dc:creator><![CDATA[Matthew Bates]]></dc:creator>
            <pubDate>Tue, 15 Mar 2022 19:08:15 GMT</pubDate>
            <atom:updated>2022-03-15T22:24:59.011Z</atom:updated>
            <content:encoded><![CDATA[<h3>React.js &amp; Ruby on Rails — End of Phase Project: Brewery Discovery</h3><p>Having completed the last of our four coding challenges, the remainder of the course revolves around an end-of-phase project, along with our final Capstone project. While the latter is an independent endeavor, my team — comprising of two very talented individuals &amp; myself — came together &amp; produced what I believe was our most impressive application to date. I wanted to take some time to reflect &amp; share some things I believe makes the app not only fun, but also incredibly functional.</p><h4>Back-End Functionality</h4><p>Our inspiration was a hodgepodge several brainstorming sessions, but it didn’t take long at all to agree that we would focus our efforts on a singular idea. While some of our stretch goals were certainly ambitious, we ended up having plenty of time to execute almost all of them, which I’ll cover a little later on.</p><p>We began by drawing out what our table relations would look like on the back-end. Having made the switch from SQLite to PostgreSQL for our RDBMS, that was a bit of a learning curve, as well. Ultimately, we knew that we wanted a user to do two things: favorite a brewery &amp; add a beer to their “mini-fridge”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/572/1*B122LJhiJD1MTx1XUhHV2A.png" /></figure><p>With there being two options to obtain data for our application — scraping &amp; good old fashioned seed data — it became apparent that seed data would be quicker, albeit repetitive. It took nearly 2,000 lines of code to include all we needed for each brewery (a total of 36) &amp; each beer (a total of 142).</p><h4>Authorization &amp; Authentication</h4><p>One of the trickier aspects of building our application was knowing we needed to include authorization, with authentication being a stretch — but we managed to cover both. A user should be able to log in; if they don’t have an account, they should be able to register. If the user neither logs in or creates an account, their access to the website is extremely limited to our “/maps” route. Lastly, we allowed a user to have full CRUD capabilities through editing their account profile:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/715/1*j-2doM9okBZ4N0HBqevkHA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*3vyi0GT9jdRFhaawQeXHIw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/682/1*PqC7P4F9OFRje0UDpNFlmw.png" /><figcaption>Login, Register, &amp; Account Update pages, respectively</figcaption></figure><p>The logic behind our PATCH wasn’t too difficult — we simply added a conditional to prevent errors if state was not set:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/409/1*kWSTC3rfGjBZaPx0UP76aA.png" /></figure><p>Once a user is logged in (or signs up), they are immediately routed to “/home” where they are greeted based on their first name:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/618/1*O-NPWkwyMvZ2G3C76heL3Q.png" /><figcaption>The user can search via brewery or state.</figcaption></figure><p>I expanded our drop-down to show our six states that were included via our seed data; a user could search by brewery name, or search via the state the brewery is in. Each of our beer cards resembles information about the brewery itself, with a background image of the brewery &amp; its logo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/576/1*1buatGeRVmVWwBEmiStKrg.png" /><figcaption>A snip-it of Ballast Points’ card.</figcaption></figure><p>Once the user clicks on a brewery, you’re directed to a real-time list of flagship beers you’ll find year-round, along with ABV &amp; beer type. One of the coolest aspects is the fact you’re able to add that beer to your “mini-fridge, where it will persist, even if you log out &amp; log back in:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*VtTh2rGd0q7GAVBGM6LJGA.png" /><figcaption>Each brewery displays their flagship beers.</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qf_jkpi0gNg5MWVQxOXizA.png" /><figcaption>Here, I have added Sculpin to my mini-fridge.</figcaption></figure><h4>Stretch Goal — Google Maps API</h4><p>Something I’m incredibly proud of adding to our application is the Google Maps API. In addition to adding the basic functionality, I added some logic for the user. Using geolocation, the user can see a list of breweries in their area. I’m located in Manitou Springs, CO and when I hit route to “/maps” I can see some of the great breweries located near me via a marker/view window I also coded in to include some information about each brewery:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/453/1*WPMGnAD0yskSAHtOrf-r4w.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/377/1*w9yNOo_cWwgt90PeIrjgpw.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*05GQyVB9gbautcke_xFAcw.png" /><figcaption>Snip-it of our “/maps” route.</figcaption></figure><h4>Wrapping Up</h4><p>As far as deployment goes, we are still tweaking a few features on the app, namely adding a lot more data to include more locations/beer. We also want to add some logic to help recommend a brewery based on your mini-fridge selection, which has been a bit of a headache as well.</p><p>I’m thrilled with the progress I’ve made, in both styling but mainly functionality. As I continue to brainstorm what I’ll be doing for my Capstone, the knowledge &amp; skills gained from this endeavor will certainly enrich what I’ll create for our last project.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=12ad3dc1b90f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ActiveModel::Serializer & Custom Serialization]]></title>
            <link>https://medium.com/@matthewhcbates/activemodel-serializer-custom-serialization-48bef009db0d?source=rss-32ec8b880104------2</link>
            <guid isPermaLink="false">https://medium.com/p/48bef009db0d</guid>
            <dc:creator><![CDATA[Matthew Bates]]></dc:creator>
            <pubDate>Tue, 01 Mar 2022 03:28:26 GMT</pubDate>
            <atom:updated>2022-03-01T16:24:27.274Z</atom:updated>
            <content:encoded><![CDATA[<p>ActiveModel Serialization — what on Earth could that possibly mean?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*foNyLgnWEB9vTFu8.gif" /><figcaption>GIF provided by <a href="https://tenor.com/">Tenor</a></figcaption></figure><p>No…not that.</p><h4>So…What’s An ActiveModel Serializer?</h4><p>ActiveModel Serializers — or AMS — provides an easy way to customize how the data rendered by our controllers is structured. This process translates a data structure/object &amp; converts it to a JSON or XML format, although the former is more often used. It takes the “convention over configuration” approach that is so often mentioned in <a href="https://guides.rubyonrails.org/index.html">RailsGuides</a>, meaning that AMS follows the same naming conventions as class/file names. More specifically, when creating your Serializer, you’ll want them to contain the same, <em>singular </em>naming pattern as its associated model. I’ll begin with how you’ll set up a brand-spanking new serializer.</p><h4>Generating A New Serializer</h4><p>Assuming that you have your <em>controller.rb</em>, <em>model.rb</em>, &amp; <em>routes.rb</em> files set up, your associations properly mapped, etc., let’s hop on over to the CLI and generate a Serializer. It will be absolutely necessary to ensure we have the “active_model_serializers” gem installed in your Gemfile by inserting the following code in the file directly:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/236/1*vDPvJKJwMYHCbLxpb45Bkw.png" /></figure><p>next, run “bundle i” in your console; if all goes well, you should see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/486/1*0dqPurEYV6qr3VoNSGzHtw.png" /></figure><p>Great! Our first step is down — let’s actually create some Serializers, now! If you’ve been following along with my <em>Medium</em> rants, you might’ve noticed that I’m a dog person, so I’ll be working off the last Rails API that I created. Since I have my <em>dog.rb</em> model already set up, I’ll remain on the CLI &amp; input the following command to initiate a new Serializer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/350/1*gZRnqBXlCAxWc6Y-xkYFtQ.png" /></figure><p>Which will create a new folder located inside <em>app</em>, with our Serializer file inside the file. Congratulations, you’ve created a new Serializer!</p><h4>We Generated A Serializer — Now What?</h4><p>Our API data would look pretty lousy if we didn’t have relevant JSON data to send back to the client; in my case, I’ll branch off of the seed data I created for my last blog &amp; include some additional attributes. Here’s how the Serializer file looks in its current state:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/344/1*5nf9EeLE6m0FRZ0hTFAOlw.png" /></figure><p>If we were to look in the browser, all that would be displayed is each instance’s :id, which isn’t very helpful:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/216/1*ozDYMs5qjxey6TvHRlVY2g.png" /></figure><p>The reason for this is that by default a new Serializer will only display the :id; I’ve since gone ahead and created some new attributes for mydog friends via seed data &amp; added it to my Serializer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/442/1*NWGcDZyC6l1LvIKJ5gc0DQ.png" /></figure><p>Which in turn renders the updated information to the browser:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/242/1*1gClzXGQfhTkrPTFvwKuvQ.png" /></figure><p>Success! Adding attributes that we want to explicitly include through our Serializers is a powerful way to control the data we send as a JSON response to the client.</p><h4>Serializing Associations</h4><p>We have our dog attributes, but what happens if I want to include some additional information, say the owner of a dog instance, veterinary information, etc.? Well, I can nest information based on their associations:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/274/1*hQ1-vpnfT7Ol0mOJjbnJFw.png" /></figure><p>I have a <em>dog</em> &amp; <em>vet</em> class that contain many-to-many associations, with <em>dog_vets </em>being the “joiner” — I want to display each dogs’ veterinary information nested under each dog instance. AMS allows us to use the same macros in the serializers that we use to set up associations in our model files, &amp; they’re smart enough to even recognize “has_many…through” associations — cool! To reiterate, this is due to AMS following the same naming conventions as class files/names:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/440/1*dLqyFBbbVjqePwiR7rB-lQ.png" /></figure><p>Let’s now take a look at my first dog instance, &amp; see what’s changed since adding the “has_many :vets” association to the dog Serializer:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/304/1*YsCPAff6dnafWXGYt811zw.png" /></figure><p>Awesome! I can now see not only the first dog instance, but also its related veterinary information!</p><h4>Creating Custom Serializers</h4><p>As you add more attributes &amp; macros to your Serializers, the level of complexity ramps up, quickly. Additionally, it’s not always necessary to include all the nested information from an association. Enter: custom Serializers! To do this, you’ll add a new, streamlined Serializer including only information relevant to what you’ll want displayed. Say I want to only display the first/last name of the vet for a particular dog instance — let’s create a custom Serializer to display only that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/396/1*nMO80NdNVfLqyJTP3-canw.png" /></figure><p>Recall that Rails automatically selects the serializer based on naming conventions, so it’s still using <em>dog_serializer.rb</em> to render the data. To fix this, we’ll have to explicitly include the Serialization method to say, “we want to render pets attributes, but only the :id, :first_name, &amp; :last_name per our customer Serializer”:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/437/1*b75B1hfBpKuBxjU9BP0HiA.png" /></figure><p>With this, the browser will render our requested information:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/228/1*XgiQYMsEVx0e191NAJfyuw.png" /></figure><p>WHOA.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*poOiQwtO-vKRiOyq.gif" /><figcaption>GIF provided by <a href="https://tenor.com/">Tenor</a></figcaption></figure><h4>Wrapping Up</h4><p>Serialization is still a new concept, but it’s quickly becoming apparent how powerful they can be at controlling what information is sent back to the client, depending on the path. Thank you for reading, &amp; if you have any questions or comments, please feel free to leave them!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=48bef009db0d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails: Routing & Custom Rendering]]></title>
            <link>https://medium.com/@matthewhcbates/rails-routing-custom-rendering-c7084b31f272?source=rss-32ec8b880104------2</link>
            <guid isPermaLink="false">https://medium.com/p/c7084b31f272</guid>
            <dc:creator><![CDATA[Matthew Bates]]></dc:creator>
            <pubDate>Thu, 24 Feb 2022 23:17:17 GMT</pubDate>
            <atom:updated>2022-02-24T23:22:25.198Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/220/0*mZvwhGdzy2a_Lk2P.gif" /><figcaption>GIF provided by <a href="https://tenor.com/">Tenor</a></figcaption></figure><p>I’ve been looking forward to working with the Rails framework since I learned Ruby. If you’re not familiar: Rails is a web application development framework written in the Ruby programming language. Some might consider <a href="https://guides.rubyonrails.org/index.html">RailsGuides</a> to be the end-all of references, so I would highly recommend checking it out if you haven’t already! Digressing a bit, I want to talk about some rather important topics that helps make Rails such a powerful tool. But first, let’s cover how HTTP works at a high-level.</p><h4>HTTP Data Flow</h4><p>When a user attempts to go to a page on a Rails application, several things happen:</p><ol><li>A client send a request to the server (i.e., types in a URL)</li><li>The server receives the request; the app’s router interprets it &amp; sends a message to the controller mapped to that route</li><li>The controller uses the model (Rails is the “M” in MVC) to access data from the database</li><li>The controller uses that data to render HTML or JSON</li><li>The server returns an HTTP response, which contains the HTML or JSON data</li></ol><h4>Generating a Rails API</h4><p>Let’s first create a new Rails API from scratch — I’ll walk through this process briefly. First, I’m going to navigate to my terminal &amp; enter the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/335/1*LbcEPs69q7tYbPKu3rUVdQ.png" /></figure><p>I’m using the “- -skip-javascript” flag as I won’t be focusing on any front-end development; additionally, “- -minimal” skips a lot of Rails features I won’t need, like image processing, at least not for now. Now we can get to work!</p><h4>Routing</h4><p>At its heart, routing allows your application to know what code to run when it receives a request. In a Rails application, you’ll find the routes file by navigating to <em>config/routes.rb:</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/158/1*LD--kNX4G6WFSaF2Or4N1w.png" /></figure><p>There’s a couple ways you can add routes, but I’ll solely focus on resource routing as it’s much more dynamic. This will allow you to quickly declare all of the common routes for a given controller. Rails’ RESTful conventions allow you to incorporate whatever CRUD operations you’ll need; by default, resource routing captures every operator at once, as seen from the following screenshot:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/397/1*DThtJ60w0myI3S8unCCh5w.png" /></figure><p>As a rule, you should <em>only</em> generate routes that your API is actually using. Otherwise, your API’s consumers will get an unexpected response if they try to use a route that doesn’t exist. As you might expect, there’s a fix for that! Shallow nesting allows us to pick-and-choose which actions we’ll be using. For simplicities sake I’ll be using three: #index, #show, &amp; #create. Here’s how that would look:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/404/1*HEfHSEvWZqkjXJUOmPwfGQ.png" /></figure><p>Using “only:” limits the resources strictly to the input(s) given — cool! Now that my collection actions are accounted for, I’ll go ahead &amp; utilize a Rails generator to efficiently create several files I’ll need with the following command:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/517/1*D4qVe0t1ZTvOO3lHAuDF9Q.png" /></figure><p>While I could have used “rails g (short for generate) models”, resource creates a couple additional files that will house my controller actions defined in <em>routes.rb</em>. Now I have my migration set up, my <em>dog.rb</em> model, along with my <em>dogs_controller</em>.</p><p><strong>Aside</strong>: I ran “rails db:migrate db:seed” to initialize my migration and some quick seed data I created.</p><p>It’s time to define my controller actions so we can render some data on the Rails server! Jumping over to <em>dogs_controller.rb</em> I’ll need to create three actions (think: methods) that I have set up in <em>routes.rb:</em></p><ol><li>#index will display all dogs</li><li>#show will show one specific instance of a dog (via params)</li><li>#create will create a new instance of a dog</li></ol><p>Keeping it high-level &amp; not diving into validations, let’s create those actions:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/425/1*B4vQRVGcZYYItxzch2zlkg.png" /></figure><p>Via route params, I’m able to search for a specific dog by looking up what’s unique to each instance of dog: its ID. So, by navigating to the URL and including the path of “/1” I’m able to render the first instance of dog, in this case:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/382/1*NQNtuRoKcdEuyb9cWXaqsg.png" /></figure><p>As well as create a new dog instance (I used <a href="https://www.postman.com/">Postman</a>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/275/1*IMoLhoz_49-w8MB2CN2zwg.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/333/1*WcVdhQ94SzdPZ96b2vHa3Q.png" /></figure><h4>Custom Rendering</h4><p>Sometimes, when sending JSON data (such as an entire model), we don&#39;t want/need to send the entire thing— this is where custom rendering can come in handy! There are several techniques to remove content when rendering your data — I’ll touch on a couple of them.</p><p>By default, using “render json:” will include all the attributes from our Active Record model that are defined in its schema. To bypass this, a widely-used technique is to include the “only:” option directly after listing an object/array of objects we want rendered to JSON:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/420/1*DyeUVaQyS7VBK8bBzuGnBQ.png" /></figure><p>Now, if I refresh the browser only the two attributes I want included will show up, excluding the remaining attributes (timestamps, in this case):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/295/1*mdm7qs_g8TCnQtX72Xy4tg.png" /></figure><p>Conversely, the “except:” option will do just the opposite: list the attributes we want excluded, displaying the remaining attributes (the same browser result will display as above):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/421/1*Q28flA8zi7anDEd83IugvQ.png" /></figure><p>Custom rendering can really come in handy when you only want/need to display certain attributes from your API.</p><h4>Wrapping Up</h4><p>I hope that these topics provided at least a kernel of insight if you are just starting out using Rails. Being such a powerful framework, there’s certainly much more I look forward to learning about it as time goes on. If you have any questions or comments, please feel free to share them!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c7084b31f272" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ActiveRecord: Associations & Seed Data]]></title>
            <link>https://medium.com/@matthewhcbates/activerecord-associations-seed-data-5a493bf7393e?source=rss-32ec8b880104------2</link>
            <guid isPermaLink="false">https://medium.com/p/5a493bf7393e</guid>
            <dc:creator><![CDATA[Matthew Bates]]></dc:creator>
            <pubDate>Tue, 22 Feb 2022 20:30:24 GMT</pubDate>
            <atom:updated>2022-02-23T19:43:10.886Z</atom:updated>
            <content:encoded><![CDATA[<p>In my last blog entry I covered ORM’s (Object Relational Mapping), &amp; how they are able to accesses a relational database using an OOP (Object Oriented Program). Furthermore, how one particular ORM framework — ActiveRecord — has lifted the burden by writing <em>far</em> less SQL. However, I left off just shy of acquiring a very powerful tool that ActiveRecord holds: associations. But what are associations, exactly, &amp; how can they make our lives easier? Most importantly: is it a hard concept to grasp?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*PG3Ppw-CTk_cXxZY.gif" /></figure><p>So — let’s dive right in!</p><h4>What’s An Association Method?</h4><p>My most often used resource when sifting through the undoubtedly endless amount of online forums describes associations as, “<a href="https://guides.rubyonrails.org/association_basics.html">… <em>a connection between two Active Record models</em></a>”. Thus far, I’ve worked solely with applications that only have a single model — take my Dog class from my previous entry, for example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/854/1*Vn_WjWk5x1wlmHteZkXLTg.png" /></figure><p>…etc., etc. I don’t wan’t to write the <em>whole class</em> out — that’s not the point! So far, it’s all been dealing with just one class (model). However, it’s certainly possible for data to be stored in multiple, associated tables; so, the following question begs an answer: “ How can we use Active Record to access that data across multiple tables?” Enter: associations!</p><h4>Visualizing Model Data</h4><p>As it happens, ActiveRecord makes it quite simple to implement one-to-many &amp; many-to-many relationships between multiple models. To do this, a couple things need to happen:</p><ol><li>Write a migration that creates tables with associations</li><li>Utilize ActiveRecord macros in said models to generate additional methods to create relationships between our tables</li></ol><p>Let’s take a look at the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/601/1*L7SF31LYTgh_xDELVmmu7A.png" /></figure><p><em>Quick aside</em>: I’m skipping over the <em>one-to-many</em> association method. As programmers, we should get used to working with large data sets, i.e. multiple tables! In a <em>one-to-many </em>scenario, my dog would <em>belong to</em> an owner &amp; an owner would <em>have many</em> dogs. Onwards!</p><p>How can we link these three tables together in such a way that we can eventually allow these three tables to talk to one-another? This is where we can define the <em>many-to-many </em>association:</p><ul><li>An owner can have many dogs</li><li>Conversely, a dog can have many owners (just an example, but I would certainly hope not! I suppose adoption would count?)</li></ul><h4>Creating Migrations</h4><p>If the above hypotheticals could happen where both the owners and dogs could have many of each, a joiner table would be necessary — dog_owners. This is extremely simplified. It might make more sense to have used users/games/reviews tables as an example (with reviews being the joiner table). However, I’m a dog person, so naturally this is where I went. Let’s build out our tables in Ruby through a <em>migration</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p7DhKjiab73gZJHglleu2g.png" /></figure><p>Per <em>The Rails Guides</em>, “<a href="https://guides.rubyonrails.org/active_record_migrations.html">Migrations are a convenient way to alter your database schema...You can think of each migration as being a new ‘version’ of the database.</a>” I’m simply creating several migrations to generate three tables in my text editor:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/427/1*9mOjX1rpb4EeSHCsCDSexg.png" /></figure><p>You might notice that each table column I’m creating corresponds with my table map I defined above, including their data types. Great! We can see that the <em>dog_owners </em>table (again, this “joins” our dog/owner tables) references both “:owner” &amp; “:dog”; by using “.references” we automatically define the relationship in dog_owner. Let’s create some ActiveRecord models &amp; set up our relationships (remember, classes are <em>singular</em> &amp; tables are <em>plural</em>):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*LScvpBCHDCI7Aa3-xMrrzw.png" /></figure><p>I have set up my three models on the same page for simplicity’s sake. Since our DogOwner class connects our Dog &amp; Owner classes, you’ll notice that its association macros “belongs_to :owner; belongs_to :dog”; conversely, our Dog &amp; Owner classes “has_many :dog_owners”. By adding the second macro for Dog &amp; Owner (&amp; using the “through:” option), we’re now able to use that #owners instance method with our dogs, &amp; vice-versa.</p><h4>Confirming Associations</h4><p>To ensure that my association macros are set up correctly, I’ll create some <em>seed data </em>which allows me to populate my database with an initial set of data:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/388/1*faDSRZ_7bAAO4_y_DXVjTw.png" /></figure><p>For the final step, let’s check to make sure our associations are correctly connected! I’ll hop into a <em>rake console</em> session to do so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/647/1*RV6Q8siUhPMSW8iv3D73-A.png" /></figure><p>Albeit a little hard to read, you’ll notice that calling “Dog.all” &amp; “Owner.all” retrieves all of the dog instances &amp; owner instances, respectively. Thanks to our joiner table, I can call “Owner.first.dogs” to display the first owners’ dogs; additionally, “Dog.first.owners” displays the first dogs’ owner.</p><h4>Wrapping Up</h4><p>There is much more to ActiveRecord associations, macros, etc.; my hope is that this high-level overview provides insight in how we can join tables using a <em>many-to-many</em> association, &amp; test our associations using seed data. If you have any questions, comments, etc., please don’t hesitate to reach out!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5a493bf7393e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruby: ORM & ActiveRecord]]></title>
            <link>https://medium.com/@matthewhcbates/ruby-orm-activerecord-7217bde43da4?source=rss-32ec8b880104------2</link>
            <guid isPermaLink="false">https://medium.com/p/7217bde43da4</guid>
            <dc:creator><![CDATA[Matthew Bates]]></dc:creator>
            <pubDate>Tue, 08 Feb 2022 01:51:26 GMT</pubDate>
            <atom:updated>2022-02-23T19:17:32.757Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been introduced to countless acronyms during my time at Flatiron School, each one seemingly more daunting than the last. After diving headfirst into ORM, or <em>object relational mapping</em>, it was clear that this was going to be an anxiety-provoking process to firmly grasp. However, if you are coding in an object-oriented language such as Ruby, being able to harness the full power of an ORM will not only simplify, but organize the usage of a relational database (such as SQLite, which is what I’m currently using).</p><h4>What Does An ORM Do?</h4><p>ORM is the technique of accessing a relational database using an object-oriented programming language. There’s no special magic to an ORM — it’s simply a manner in which to implement code that connects an OOP to a database; think of it as being a middle-man between a relational database and your OOP of choice. This process is referred to as “mapping” &amp; can be described as the drawn connectors between the database and our language models:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/562/1*LH9Wgh3Fs5YigiaXcPy8fw.png" /></figure><p>What’s special about this process is that it allows us to connect a database table like a Ruby class, &amp; the database rows like instances of a class. However, we’re not actually saving Ruby objects to the database. Instead, we take the individual attributes of a given instance &amp; save them as a row in our table.</p><h4>ORM Framework &amp; OOP Interaction</h4><p>Let’s talk about how ORM’s &amp; an OOP, such as Ruby, interact. Below, I have manually created a table that I’d like my code to produce to list dog instances, along with their attributes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*84WKlpi5piWsV1fc461wlA.png" /><figcaption><em>Note: I’m using 0 for false &amp; 1 for true</em></figcaption></figure><p>Now, we can use the SQL function INSERT INTO to painstakingly hard-code the information into our table, one-by-one. This would be very inefficient:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3amgaAUlvWxyJEPGjMn2ww.png" /></figure><p>It would be proper to write out our Dog class in our OOP so that in the instance more dogs are added to the list, we can write a couple class methods that will simplify/save us the trouble of writing the above many, many more times:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/954/1*Q9x0VG8_eR6BoNb94Z6iaA.png" /></figure><p>Thanks to our two class methods <em>self.all</em> &amp; <em>self.save</em>, any new dog instance can now be “shoveled” (think: “pushed”) into our array denoted by our class variable “@@all” — cool! Yet, is there <em>another</em> method that could take some of this heavy-lifting off our shoulders?</p><h4>Enter: ActiveRecord</h4><p>ActiveRecord is an ORM framework , a Ruby gem containing an entire library of code. It’s one of the most widely-adopted among users of Ruby. Thanks to c<a href="https://guides.rubyonrails.org/active_record_basics.html#convention-over-configuration-in-active-record">onvention over configuration</a>, it’s possible to write very little configuration when creating ActiveRecord models. What’s this mean? Well, for starters, it means writing <em>far</em> <em>less</em> SQL; additionally, it enables us to call SQL functions in a more intuitive manner. More so, it allows users to interact with data using CRUD methods you may already be familiar with. When a class inherits ActiveRecord::Base, your class has access to basic CRUD functions!</p><p>To begin, we’ll need to tell Active Record where the database is located it will be working with, via ActiveRecord::Base.establish_connection:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/600/1*EwibI3j4kOJQ2RoYkHaaug.png" /></figure><p>ActiveRecord::Base keeps it stored as a class variable at ActiveRecord::Base.connection. Below, the code in-between is simply creating a new table with our previously-established attributes for our Dogs class:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/664/1*KuwSi84uCjQ9lXzpJS0ptA.png" /></figure><p>The final step is to tell your Ruby class to make use of Active Record’s built-in ORM methods. To do this, we make our class Dog a subclass of ActiveRecord::Base — this is known as <em>Class inheritance</em>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/466/1*2BY_c9uMa4ue5lJiJDL4Zg.png" /></figure><p>It should be noted that it’s <em>very</em> important to remember to make your Class names <em>singular </em>(Dog) &amp; your table names <em>plural</em> (dogs).</p><p>Every time we wanted to create a new dog instance, we just inherit those features from ActiveRecord; instead of our lines &amp; lines of code above to instantiate &amp; save a new dog, we are able to use ActiveRecords built-in create function to add a new dog row to the dogs table:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/740/1*UoVI4rlzfi5fFqrGZuBhhg.png" /></figure><p>Pretty neat, right?</p><h4>Wrapping Up</h4><p>Having been introduced to ActiveRecord after learning ORM fundamentals was a breath of fresh air for me. Not only did it allow to streamline &amp; reduce the amount of code I had to write, it’s also an incredibly powerful tool. For more information on the seemingly unlimited amount of possibilities of ActiveRecord, I highly recommend stopping by <a href="https://guides.rubyonrails.org/index.html">here</a> to check it out!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7217bde43da4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruby: @Instance & @@Class]]></title>
            <link>https://medium.com/@matthewhcbates/ruby-instance-class-1fafa69e44f?source=rss-32ec8b880104------2</link>
            <guid isPermaLink="false">https://medium.com/p/1fafa69e44f</guid>
            <dc:creator><![CDATA[Matthew Bates]]></dc:creator>
            <pubDate>Thu, 03 Feb 2022 19:17:20 GMT</pubDate>
            <atom:updated>2022-02-03T19:18:46.016Z</atom:updated>
            <content:encoded><![CDATA[<p>Ruby is based on the concept of Object-Oriented Programming, or OOP as it’s commonly referred to. It’s a style of programming that’s based on the concept of “objects,” which you can think of as containers for data. One of the goals of OOP is to create programs using — you guessed it — objects that share common functionality. So, what are instances &amp; classes, exactly? Let’s dive into that a bit, &amp; describe their relationship to OOP.</p><p>In general, Ruby’s OOP comes in the form of writing out your program into separate classes, which subsequently house instances. Classes essentially houses/standardizes your collection of data, while an instance is a unique chunk of that data. Both classes &amp; instances can contain methods, which at a high-level contain a set of expressions that return a value; additionally, they both can contain variables. First, let’s touch on methods a bit.</p><h4>Class &amp; Instance: Methods</h4><p>If you read my previous blog on Ruby, you’ll recall that methods are initialized with the “def” keyword, &amp; uses “end” to identify where the method ends — your code, naturally, falls in between. A class Method will directly affect/access information from the class itself; an instance method directly affects/accesses information from the instance it’s being called on. There are some subtle differences, however, when it comes to initializing a class/instance method. Let’s look at the following, &amp; break them down a bit:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/790/1*9U2fsvsYYzONznTlgkul3Q.png" /></figure><p>When <em>Example.class_method</em> is called below, it returned the puts statement in the method since it was called on the class itself (ignore the “nil” — this is standard output as “puts” will always return this). When <em>Example.instance_method</em> is called, undefined is returned because at this point there is no instance of the class specified in which to call the method on.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*sK-xFzc-VA5vz-3iYHQjjA.png" /></figure><p>If you take a look below at the this second example, a new instance of the class was created (Example.new), so the opposite occurred.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*J5BwD-POELfEimNcOrigMw.png" /></figure><p>A couple key takeaways:</p><ul><li>Class methods can <em>only be called on classes</em>; they are <em>always</em> defined with def <strong>self</strong>.method_name</li><li>Instance methods can <em>only be called on instances of classes</em>; they are <em>always</em> defined with def method_name</li></ul><h4>Class &amp; Instance: Variables</h4><p>You might have noticed in my title I included those “@” symbols. Let’s talk about how those tie into class &amp; instance variables! First off, instance variables have different values for each object instance, &amp; are defined by “@instance_variable_name”. Conversely, class variables have the same value across all class instances &amp; are defined by “@@class_variable_name”. Take a look at the following:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/464/1*eWryZMJYW-5c84ZQFvcLxQ.png" /></figure><p>What you might notice is that we set a default value for album_count of zero, along with an instance variable <em>name</em> set with <em>attr_accessor</em> (if you’re not familiar, this essentially replaces our “setter &amp; getter” methods). Inside initialize, the instance variable is set to an argument of name; what this allows me to do is, right after instantiating a new instance, I’m able to set a unique name to each individual instance. But if you take a look at this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/394/1*0tQAXKwyJUd1Sa7x57EUvg.png" /></figure><p>You will see that, with my class method, I was able to call <em>Album.count</em> and log how many instances I have created within that class method, which is currently three. This makes sense: class variables are typically used to store information regarding the class as a whole; they enact behaviors that belong to the whole class, which includes each instance!</p><h4>Bonus: Self</h4><p>Above, if the class method above using the term “self” might not be apparent to you, well, it wasn’t to me at first, either. I did not include any instance methods in my examples using self, but at a high-level, it’s pre-set variable used inside of a method that dynamically points at the object at which its called upon. Above, my method targets a class &amp; becomes a “reference point” to that class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/498/0*5GDk9ImziUDSkShX.gif" /><figcaption>GIF courtesy of <a href="https://tenor.com/">Tenor</a></figcaption></figure><h4>Wrapping Up</h4><p>Ruby’s an Object-Oriented Programming language that allows for a tremendous amount of flexibility in regards to how you structure your code. While I only touched on a couple fundamental topics, class/instance methods &amp; variables are an integral part of writing in Ruby. I hope that I was able to provide some clarity, &amp; I gladly welcome any feedback or comments.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1fafa69e44f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>