<?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 Ian McManus on Medium]]></title>
        <description><![CDATA[Stories by Ian McManus on Medium]]></description>
        <link>https://medium.com/@ianmcm.89?source=rss-e3a1b0e55f7b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*OdI4EoYdJyXmBSPLqiM1NA.jpeg</url>
            <title>Stories by Ian McManus on Medium</title>
            <link>https://medium.com/@ianmcm.89?source=rss-e3a1b0e55f7b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 16:23:06 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ianmcm.89/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[Uploading image files using React, Rails Active Storage, Cloudinary and Heroku]]></title>
            <link>https://medium.com/@ianmcm.89/uploading-image-files-using-react-rails-active-storage-cloudinary-and-heroku-104b6bce7c6f?source=rss-e3a1b0e55f7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/104b6bce7c6f</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[code-newbie]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[active-storage]]></category>
            <dc:creator><![CDATA[Ian McManus]]></dc:creator>
            <pubDate>Mon, 26 Sep 2022 04:31:01 GMT</pubDate>
            <atom:updated>2022-09-26T04:34:08.027Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*ML993ypssoycG3OqG3h4ZA.png" /><figcaption><a href="https://pixabay.com/illustrations/cloud-computing-cloud-upload-file-1990405/">Image</a> by <a href="https://pixabay.com/users/tumisu-148124/">Tumisu</a>, <a href="https://pixabay.com/">Pixabay.com</a>, Licensed under CC0</figcaption></figure><h4>The Final Countdown</h4><p>Well folks, the day has finally come…I find myself at the end of my journey at Flatiron School, with only this blog post and my final project review standing in the way of graduation. Oh what a good feeling that is…</p><p>For my final project, I decided to create an app called GeoPlanner, an event planning app centered around Google’s places API, or more specifically, <a href="https://www.npmjs.com/package/react-google-maps">react-google-maps</a>, available from <a href="https://www.npmjs.com/">npmjs</a>. I’d recommend react-google-maps to anyone trying to utilize a Google map in their React projects for the first time. It’s relatively simple and easy to use for a newbie and you can troubleshoot issues fairly easily by just googling them. But I digress…</p><p>GeoPlanner, in a nutshell, allows a user to search for places using a dynamic Google map, select a location via its marker and then create and post an event centered around that location.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*JuRxiI9H7UPW2hu0f1vsGA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YhxkI9wttV00zwe94Xz40Q.png" /></figure><p>The user can search for and request friends using a provided search bar and, once approved, view their nearby friends’ events on the same map.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IwdaZPp32wpXbpOxQBssWQ.png" /></figure><p>The app is relatively simple, straightforward and polished on the outside, but dive into the code and well…lets just say developing this app brought me into some new and unexplored territory.</p><p>While I had to nix some functionality and stretch goals that I wanted to include in favor of time constraints (looking at you, WebSockets), I was able to include once important feature that really tied the app’s social aspect together.</p><h4>So how DO you upload files anyway?</h4><p>The file input tag is one of those things that you&#39;ve probably seen as a budding coder in your travels across the web, but never actually used. Such was the case for me when developing my app. I wanted a user to be able to upload an image file of themselves to associate with their account, so that the map overlays could have a nice little thumbnail image of their faces next to their events for their friends to see on the map (see image above). You <em>could</em> simply click the event popup and see the username of the event poster, but where’s the fun in that?</p><p>So I dove into the internet and found my solution, the <a href="https://www.w3schools.com/tags/att_input_type_file.asp#:~:text=The%20%3Cinput%20type%3D%22file,selected%2C%20add%20the%20multiple%20attribute.">file input tag</a>, which looks like this in your html file:</p><p>&lt;input type=”file” id=”myfile” name=”myfile”&gt;</p><p>This is great and all, but it’s a bit crude and we’ll need to jazz it up a bit if we want it to work for us.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oAbrYxI8lEW8snyZJMtkxA.png" /></figure><p>We need to add the image types in order to tell our file input what to accept. I only want to accept files of type .jpeg or .png so I’ve added accept=”image/png, image/jpeg” to my input. The multiple={false} is optional and just tells my input not to accept more than one file. I&#39;ve also added an onChange event handler to handle the file state. Finally, make sure to add encType=”multipart/form-data” to your form input. We’ll need this later in our request.</p><p>Ok great, so we’ve got our input tag all ready to go, but it doesn&#39;t really do anything yet. In comes <a href="https://edgeguides.rubyonrails.org/active_storage_overview.html">Active Storage</a>.</p><h4>Active Storage</h4><p>So what is Active Storage? According to the Rails docs:</p><blockquote>Active Storage facilitates uploading files to a cloud storage service like Amazon S3, Google Cloud Storage, or Microsoft Azure Storage and attaching those files to Active Record objects. It comes with a local disk-based service for development and testing and supports mirroring files to subordinate services for backups and migrations.</blockquote><p>That’s a lot of technical jargon, but basically, Active Storage acts as the middleman between your front end and your back end and lets you store those files you uploaded somewhere, either locally or in the cloud. So let’s go ahead and set up Active Storage on our app by typing in rails active_storage:install into our terminal.</p><p>This will create two new migrations in our rails backend, create_table :active_storage_blobs and create_table :active_storage_attachments</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n5V_NhivBxpsA5iQ-6WCbA.png" /></figure><p>Don’t stress about the significance of these tables too much, in fact the only thing we’re really going to take away from these tables is the first attribute in the :active_storage_blobs table, t.string :key, we&#39;ll need this later to generate our Cloudinary URL. Just go ahead and migrate your changes by running rails db:migrate and we’ll move on to the next step.</p><h4>Rails Backend Setup</h4><p>Next we need a model to associate a file with. For my app, I used the User model I already had since I want my users to be able to attach files.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*HAlRRbTsjwoyApay27XvqQ.png" /></figure><p>The association is very simple and straightforward, just add has_one_attached followed by the attribute name of whatever you want your attribute to be called. In my case I want users to be able to add an :avatar to their account. You can also change the association tohas_many_attached for multiple files, but that’s beyond the scope of this blog. Now, onto the controller…</p><p>In my users_controller, I created a new method called attach_avatar. This method simply finds the current user and calls the .attach() method on the user’s :avatar attribute, passing the :avatar params provided by my form on the front end (more on that in a bit).</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BDpDTnXZujlFvjj8HrGjFw.png" /></figure><p>Make sure to add :avatar (or whatever you decide to call your attribute) to your permitted parameters. If you plan to include other params in your front end post request, it’s a good idea to append .select {:avatar.present?} to the end of your params, otherwise your rails console will throw an error when you try to pass other parameters with your file attribute while it’s still null, such as in a form object like so:</p><pre>{ <br>  username: ‘’, <br>  password: ‘’, <br>  avatar: null <br>}</pre><h4>Cloudinary Platform</h4><p>Now, by default, active storage stores images you upload in a file in your local environment. This is all well and good for development, but what if we want to utilize Active Storage for production? How can we have our users upload their image files if they don’t have access to our local storage? The answer isn’t so much <strong>how?</strong> as <strong>where?</strong></p><p>Enter Cloudinary, a free, easy to integrate cloud storage platform for files and attachments. Start by first signing into your Heroku account and from the <strong>resources</strong> tab, search for <strong>Cloudinary — Image and Video Management </strong>under add-ons.<strong> </strong>Follow the on screen prompts and this will create a new Cloudinary account linked to your Heroku project.</p><p>Next, navigate to your new Cloudinary account and under the <strong>dashboard</strong> tab, look for <strong>API Environment variable</strong> and click the copy button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*B5sBcuseWvcTIYy3bFTaqg.png" /></figure><p>Then, navigate back to your Heroku account, click <strong>settings</strong>, click <strong>Reveal Config Vars</strong> and paste the url in the value field (make sure it starts with cloudinary://…) and then add CLOUDINARY_URL to the key field and click the add button. If you need more information on this step, I have a similar post on adding config vars to Heroku. Your Cloudinary credentials are now added to your Heroku app!</p><p>Now let’s head back to our code and add the following to our production.rb file in config/environments, making sure to console log out # config.active_storage.service = :local.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*zB3VCUra0drF5VAsJlsbiQ.png" /></figure><p>Finally, add the following to the storage.yml file in /config:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tz-cRPgIhN_Ruv1Dje0QpQ.png" /></figure><p>The final piece of the backend puzzle lies in the serializer. You can generate a new serializer with rails g serializer attribute_name, then define your attribute in the serializer like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*gKsi14vsp5aDBC6w145CjQ.png" /></figure><p>Remember that key attribute we noted earlier? This line of code generates a url in the backend using the uploaded image’s key found in your Cloudinary media library:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/898/1*L-NkxKPjD2KlMhpzt5-q9A.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*-KL7XuO6o5wDX6-L_QB7Pg.png" /></figure><h4>FormData</h4><p>With everything wired up, we’re now ready to make our patch request and send our shiny new file to our backend. File’s can’t be sent as stringified JSON data however, so you&#39;ll need to add the following code to your request:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/488/1*T8UuPreTlUN6RcLB-6YI0g.png" /></figure><p>avatar is whatever attribute you&#39;ve named for your model’s uploaded file records, and form.avatar is whatever state variable you&#39;ve defined for your file’s state in your React front end. Assuming everything has been added correctly, you should now be able to upload image files to Cloudinary from your react front end and then display them using the Cloudinary url saved in your backend!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*R930gvtG7ZjG_4sVibdWTg.png" /></figure><h4>Conclusion</h4><p>This has been a longer post (and arguably my longest blog post yet), but I tend to be a visual learner and I appreciate a good step by step tutorial, so hopefully I&#39;ve offered the same experience to you as well. I’ve tried to cover all the bases in this post, but I’ll leave the comments open in case I missed a step. Feel free to let me know and happy coding!</p><p>As for me, it’s been a long 1+ year road, but it’s about time for me to say goodbye to Flatiron School and Hello World! to the tech industry thanks to Flatiron School’s software engineering flex program.</p><p><a href="https://github.com/IanMcM89/phase-5-project">GeoPlanner Github Repo</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=104b6bce7c6f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Reformatting Your Timestamps in Ruby/Rails]]></title>
            <link>https://medium.com/@ianmcm.89/reformatting-your-timestamps-in-ruby-rails-a5e615732039?source=rss-e3a1b0e55f7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/a5e615732039</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[code-newbie]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Ian McManus]]></dc:creator>
            <pubDate>Sun, 04 Sep 2022 21:28:16 GMT</pubDate>
            <atom:updated>2022-09-04T21:28:16.356Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*CsS4DREzwPEV_8SeyrxMUw.jpeg" /><figcaption>Image by Pexels, <a href="http://www.pixabay.com/">PixaBay.com</a>, Licensed under CC0</figcaption></figure><p>Any coder working on a Ruby/Rails application has seen t.timestamps in their ActiveRecord migrations and the created_at and updated_at attributes the migration creates in your table. What are these attributes, and more importantly, how do we change them to make them more readable?</p><h4>Timestamps</h4><p>According to the <a href="https://api.rubyonrails.org/classes/ActiveRecord/Timestamp.html">ActiveRecord documentation</a>:</p><blockquote>Active Record automatically timestamps create and update operations if the table has fields named created_at/created_on or updated_at/updated_on.</blockquote><p>Active Record changes these attributes when a record is newly created or updated by timestamping the transaction. Typically, timestamps are already included at the bottom of your migration after generation (see below):</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/687/1*3IhQgpviHOTEAF30C8mR9g.png" /></figure><p>If you don’t want timestamps automatically added when you create a new migration, then you can simply add config.active_record.record_timestamps = <strong>false </strong>in your /config/application.rb file. You may need to rollback and re-migrate to see this change.</p><p>But what if we want to keep our timestamps for later use? Timestamps are displayed using UTC time, and are generally just difficult to read at first glance:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/526/1*6a2u1nOp5Nay51ZKt6-pIw.png" /></figure><p>2022–09–04T18:41:07.040Z…yeesh. This format will surely work, but it’s a bit crude and not very user friendly. So how do we change our created_at or updated_at attributes to make them more readable to our users or other developers working on our project?</p><p>There are several different options when it comes to achieving this goal, but today I’ll go through the option that worked for me when trying to display a more user friendly date and time for my friend request notifications in my app. The following is very heavily based on <a href="https://www.folkstalk.com/2022/07/how-to-change-created_at-format-with-javascript-rails-with-code-examples.html">this</a> short post and all credit for the solution goes to the author.</p><p>You can actually override the format of your created_at or updated_at attributes by simply adding this code in your model:</p><p>attributes[‘created_at’].strftime(“%m/%d/%Y %H:%M”)</p><p>For example, this is what the code looks like in my FriendRequest model:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/708/1*qR3D52WbzPqVHOJ-g5Nb0g.png" /></figure><p>…and the resulting date and time displayed for the friend request in my app:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/519/1*fD5Bee6Pv3ZUtiyOVBatAg.png" /></figure><p>…aaaand Voila! Much easier to read than 2022–09–04T18:41:07.040Z don’t ya think?</p><h4>Conclusion</h4><p>There may be better ways to achieve the same goal and even display local time instead of UTC, but that goes beyond the scope of this post. Displaying a nicely formatted timestamp isn&#39;t always necessary, but your users may silently thank you later when they try to determine when and at what time their friend requests, invites, alerts etc. were updated/created at and it just generally improves the overall user experience in my opinion.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a5e615732039" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to access API keys in your Heroku React app]]></title>
            <link>https://medium.com/@ianmcm.89/how-to-access-api-keys-in-your-heroku-react-app-46641bf1a746?source=rss-e3a1b0e55f7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/46641bf1a746</guid>
            <category><![CDATA[code-newbie]]></category>
            <category><![CDATA[heroku]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Ian McManus]]></dc:creator>
            <pubDate>Fri, 02 Sep 2022 17:32:52 GMT</pubDate>
            <atom:updated>2022-09-02T17:34:54.694Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*SZb9SKnlEmnYfDcCLsACBA.jpeg" /><figcaption>Image by MasterTux, PixaBay.com, licensed under CC0</figcaption></figure><p>So you’ve spent hours working on your cool new React app, you&#39;ve gone through the Heroku deployment process and now you&#39;ve finally navigated to your app’s new Heroku address aaaaand…..&lt;brain fart&gt;. Lo and behold, that cool feature you added (in my case a Google map using geolocation services) that makes API calls to a backend somewhere no longer has access to your your keys after deployment and you&#39;ve got a whole lot of red in your console. Yikes…</p><h4>Hiding Keys in Development</h4><p>Prior to deployment, the process for hiding API keys is pretty simple. Depending on your development setup, you (like me) could simply add your API key to a dotenv file by prepending REACT_APP_ to whatever you want to name the key, like so:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bQu2soupGm-gJ6L2MVAG0g.png" /></figure><p>Then, you could add that file to your gitignore so the key or keys within the file don’t accidentally get pushed to your Github repo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*26_ym2xnta_Co97O3tZj1g.png" /></figure><p>The code within your app would then simply need to call the API key from the dotenv file using the process module and env property :</p><p>googleMapsApiKey={`${<a href="https://nodejs.dev/en/learn/how-to-read-environment-variables-from-nodejs/">process.env</a>.REACT_APP_YOUR_API_KEY_HERE}`}</p><p>This approach is just fine in development and allows your code access to your API keys without ever pushing them to your GitHub repo where they can be stolen and used for more nefarious purposes (yes, there are tech savvy cyber criminals out there that comb GitHub accounts for API keys…&lt;sighs&gt; why can’t people just do the right thing…).</p><h4>Hiding Keys after Deployment</h4><p>While the above approach is simple and great for your development environment, it doesn’t work in your production environment because your ignored .env file won’t be pushed to Heroku…at least not in the way you want anyway…</p><p><strong>Important aside: </strong>your code gets packaged up in .js files called chunks during deployment and your super secret keys can later be found in the bundle.js file after deployment. Obviously we don’t want this information publicly available for key combers to find, so it is a good idea to remove any secrets from your.env file prior to going through the deployment process so they don’t get packaged up in the build. Don’t worry, we can add them to Heroku so your app still functions.</p><p>Adding your keys to Heroku config is also a relatively simple process.</p><p>First, start by navigating to <a href="http://www.heroku.com/">Heroku</a> and login to your account:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*b7sHEY-9v92D3MDyQSWT3A.png" /></figure><p>Then, once you&#39;ve logged in to your account, click the name of your Heroku project listed in your dashboard:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*eQGlSDGoArComNTZr4nomw.png" /></figure><p>Once in your project’s directory, click the <strong>Settings</strong> tab, followed by the <strong>Reveal Config Vars </strong>button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*K3GdXJefWgKbrt92zCWARw.png" /></figure><p>This will reveal your Heroku app’s config variables. There will already be some variables in the list, but don’t worry about any of these. Scroll down to the bottom of the list and you&#39;ll see blank key/value inputs with an <strong>Add</strong> button:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*c_z9jbdPl9_fy1RoedAQjg.png" /></figure><p>Finally, add your API key’s name as it was defined in your app’s.env file and value (if you choose to rename the key here in the config vars, you’ll need to change the name in your React code to the new name in order for your feature to work), making sure, once again, to prepend REACT_APP_to the name and then click <strong>Add</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*E6Lu4Grwfm3h5HHLJYy4DA.png" /></figure><p>Viola! Assuming the naming conventions match in both your Heroku config vars and in your React apps js code, you should now see your feature working in your production build sans the console errors (note: you may need to refresh your browser).</p><h4>Conclusion</h4><p>Keeping your code’s secrets private is an important part of app development and the process can be a bit of a head scratcher for a budding coder like myself post deployment. Hopefully I’ve streamlined the process for you to prevent said head scratching in the future.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=46641bf1a746" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Protecting Passwords with Rails]]></title>
            <link>https://medium.com/@ianmcm.89/protecting-passwords-with-rails-88b30edf754c?source=rss-e3a1b0e55f7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/88b30edf754c</guid>
            <category><![CDATA[code-newbie]]></category>
            <category><![CDATA[code]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Ian McManus]]></dc:creator>
            <pubDate>Tue, 14 Jun 2022 18:45:42 GMT</pubDate>
            <atom:updated>2022-06-14T18:56:28.949Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*FI3ZbhM9sLqPUbGGkGtfIA.jpeg" /><figcaption>Image provided by Pixabay, licensed under CC0</figcaption></figure><p>As the end of my curriculum in the full stack web development program at <a href="https://flatironschool.com/welcome-to-flatiron-school/?utm_source=Google&amp;utm_medium=ppc&amp;utm_campaign=12728169839&amp;utm_content=127574231184&amp;utm_term=flatiron%20school&amp;uqaid=513799628798&amp;CjwKCAjw46CVBhB1EiwAgy6M4t8dnLk3i5k4KY8vJ0f5VjcF2axKlv4pP0W_plBLqNlH0UdrniD9YRoCVGgQAvD_BwE&amp;gclid=CjwKCAjw46CVBhB1EiwAgy6M4t8dnLk3i5k4KY8vJ0f5VjcF2axKlv4pP0W_plBLqNlH0UdrniD9YRoCVGgQAvD_BwE">Flatiron School</a> draws ever closer, I find myself feeling more and more confident in myself and my code. It certainly wont hold a candle to that of a seasoned web developer with years of experience in the field (at least not yet), but it’s improving with each new lesson and each completed project.</p><p>Speaking of projects…I’ve now reached the end of phase four, the “Rails phase,” and with only one more phase to go, that makes this my second to last project before completion. An exciting and equally scary thought that I’ll soon be on the hunt for a job in the tech industry and leaving my old life and my boat-driving maritime career behind me. But I digress…</p><h4>Fitness/365</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*h5PIlpTmS_F1TAkOMA2lgw.png" /><figcaption>Fitness/365 App by Ian McManus</figcaption></figure><p>For my end-of-phase project, I decided to develop a simple exercise app, Fitness/365, that allows a user to search for specific exercises in the database, either via the interactive image map seen above, or via the provided search bar.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zg21j2Zf5MdZf5YKcL9ktA.png" /><figcaption>Fitness/365 App by Ian McManus</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uvBi5ZC0sGvdBjHDdRlS9w.png" /><figcaption>Fitness/365 App by Ian McManus</figcaption></figure><p>Each exercise contains some basic exercise data and a description (currently Latin to save time seeding entries). Users can also create new exercise posts and leave comments on their own and others’ posts.</p><h4>Password Protection</h4><p>Now that I&#39;ve introduced my app, let’s talk about how I’m securing my user’s login data.</p><p>Any great app should allow users to log in and log out. Thanks to rails, this is a fairly easy and straightforward process to implement.</p><p>First things first, after generating my user resource with rails g resource I can then navigate to the newly created user.rb file and set up my user model…</p><pre>class User &lt; ApplicationRecord</pre><pre>  has_many :comments</pre><pre>  has_many :exercises, through: :comments<br></pre><pre>  <strong>has_secure_password</strong><br></pre><pre>  validates :username, presence: true, uniqueness: true</pre><pre>end</pre><p>To protect my users’ passwords, the key line of code in my User class is <a href="https://api.rubyonrails.org/v7.0.3/classes/ActiveModel/SecurePassword/ClassMethods.html"><strong>has_secure_password</strong></a>. The rails doc explains has-secure_password best:</p><blockquote>Adds methods to set and authenticate against a BCrypt password. This mechanism requires you to have a XXX_digest attribute. Where XXX is the attribute name of your desired password.</blockquote><p>As stated, this authentication only works if you have a <em>XXX_digest </em>attribute associated with your user model, which you can see I added to my users table below as password_digest:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/997/1*QpSpPqQWIw9XkPhzSkk1Fw.png" /></figure><p>Rails automatically adds validations for password presence, length and confirmation, so the only other validations I had to enter into my user model are the validations for my :username attribute.</p><p>The next steps involve both my users and sessions controllers. A new controller for sessions can be created with rails g controller Sessions. Depending on your desired routes, the code in your controllers might end up looking different than mine, but I’ve established methods for create and show and create and destroy for both my users and sessions controllers respectively:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*1H8z78hyp8v1SzBNjj-V7Q.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5gYRfaPxZ7f9pAJJt_7zhQ.png" /></figure><p>In a nut shell, what this code does is create a new user via the create method in my users controller with the user_params I&#39;ve declared (assuming they pass the authorization check with valid data (i.e. username is unique, password and confirmation match etc.) and then the code adds the user_id to the session via the create method in my sessions controller (seen above). This method finds the user via their username and authenticates the password provided. If all checks out, the user is allowed access and added to the session so they don’t have to keep logging in every time they try to access information from the site. To remove the user from their session and prevent any unauthorized activity on their account, a user can log out, which calls the destroy method in the session controller, deleting their :user_id from the session.</p><p>What is a session you ask? Simply put, a session is a special type of cookie that is “signed” by rails via a big encrypted string that gets appended to every session cookie that rails sets, and this prevents tampering with data. You can use dev tools to edit this data, contained in cookies, till the cows come home, but the cookie&#39;s “signature” won’t match. Refresh the page and you&#39;ll find that all these changes you tried to make were reverted.</p><p>The final piece of the puzzle to get all this code working is to set up the routes for each of the methods declared in the controllers above:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*csBFJ5CGS1IC_a_e1DRvJg.png" /></figure><p>You can name the route anything you want, but I chose to keep it simple with /signup, /login and /logout. Assuming you’ve migrated the additions to your users table and your server is up and running via localhost or Heroku, a new user should now be able to be created via a sign up form and the user allowed access to your site until they click the logout button. If this user (or someone with more nefarious intentions in mind) attempts to edit cookie data to gain some sort of advantage, well…no dice.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*a-MNWEn9CIoFkPWdyOhLqQ.png" /></figure><p><strong>Conclusion</strong></p><p>Depending on the context of your App, user’s may be providing sensitive data such as bank account information, addresses, phone numbers, emails, etc associated with their accounts, and all this data should be protected via a secure sign in process that prevents tampering with sensitive information . Rails provides a means to secure user passwords through BCrypt encryption to prevent such tampering, and while it can be a little challenging to set up at first, it can provide a safe experience for your user’s knowing that their login data is secure.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=88b30edf754c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My Ruby Wrap-up]]></title>
            <link>https://medium.com/@ianmcm.89/phase-3-wrap-up-ab6b12f30e2f?source=rss-e3a1b0e55f7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ab6b12f30e2f</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[activerecord]]></category>
            <category><![CDATA[code-newbie]]></category>
            <dc:creator><![CDATA[Ian McManus]]></dc:creator>
            <pubDate>Wed, 13 Apr 2022 20:20:09 GMT</pubDate>
            <atom:updated>2022-06-14T13:13:41.388Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*2Kf8OrKaA4aqb1ft3JNoMg.jpeg" /><figcaption>Image by <a href="https://pixabay.com/users/peter-lomas-5966639/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=3185447">Peter Lomas</a> from <a href="https://pixabay.com/?utm_source=link-attribution&amp;utm_medium=referral&amp;utm_campaign=image&amp;utm_content=3185447">Pixabay</a>, Licensed under CC0</figcaption></figure><p>Once again I find myself at the end of another phase in my journey at Flatiron School. In this case, phase three, the “<strong>Ruby</strong> phase.”</p><p>Taking the leap from a simple JSON backend to creating my own backend data using Active Record was, in execution, fairly straightforward. What wasn&#39;t so straightforward, was the theoretical aspect…learning all that technical jargon that makes a Ruby/Active Record backend tick. When all you’ve learned thus far is JavaScript and its usage in a React frontend (which now seems like child’s play by comparison), Ruby and its syntax, object orientation, objects vs hashes, SQL and all the other innards that make this backend framework well…work, can seem a bit daunting to a new coder.</p><p>I do, however, understand the importance of the lesson, that Active Record is designed to make our lives easier and take the hassle out of our backend development. In order to use Active Record though, one must first understand HOW it works and what it’s doing under the hood, and that requires understanding all those aforementioned “innards.”</p><p>As a test to my knowledge of Ruby’s innards, I was once again tasked with the creation of a portfolio project. This time I searched through my interests and decided to create a simple app that allowed me to collect all the recipes I’ve tried in my cooking experience in one convenient location.</p><h4>My Recipes. App</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*83m8YlaadeX-wzIibC_efA.jpeg" /><figcaption>My Recipes Home Page by Ian McManus</figcaption></figure><p>In a nut shell, “My Recipes.” allows me (or anyone that wishes to use the app) the ability to search through recipes that I’ve added to my database for use at home. These are recipes that I&#39;ve either created myself or modified to my liking based on recipes I’ve found online and tried. The key difference, however, is that I only include the relevant information, i.e. step by step instructions and a list ingredients among a few small extras. This app was designed for efficiency in the kitchen, not to serve as a boring history lesson on the origins of a particular recipe (save that for Google).</p><h4>What worked as expected…</h4><p>After getting a basic Active Record backend directory set up, followed by running bundle install, deciding on a one-to-many association structure was relatively straightforward.</p><p>A category has many recipes…</p><pre>class Category &lt; ActiveRecord::Base</pre><pre>  has_many :recipes</pre><pre>end</pre><p>and a recipe belongs to a specific category…</p><pre>class Recipe &lt; ActiveRecord::Base</pre><pre>  belongs_to :category</pre><pre>end</pre><p>Simple. Then it was a matter of creating two separate models, one for my Category class and another for my Recipe class (see above code), creating migrations for each class and some adding some basic seed data in my seeds.rb file for categories and recipes before migrating.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*FX7zMVdvG5YHGRIBDBpAZw.jpeg" /><figcaption>Screen capture by Ian McManus</figcaption></figure><p>Writing methods for each CRUD related operation was also relatively to the point. For instance, a simple Ruby get method for /categories looks something like this:</p><pre>class CategoriesController &lt; Sinatra::Base</pre><pre>  set :default_content_type, &#39;application/json&#39;<br></pre><pre>  get &#39;/categories&#39; do</pre><pre>    Category.all.to_json(only: [:id, :name])</pre><pre>  end</pre><pre>end</pre><p>…and the resulting JSON:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Ucpg8h3RocQmQq5YUpAdIQ.jpeg" /><figcaption>Screen capture by Ian McManus</figcaption></figure><h4>Where I struggled…</h4><p>Referring back to my schema, one can see ingredients and steps attributes within the hash, each with a default value of an empty array:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6EMJbM5mVXRrjekV4_4Zdg.png" /><figcaption>Screen capture by Ian McManus</figcaption></figure><p>For a newbie like myself, figuring out how to convert this array from Ruby to JSON, particularly without having any knowledge of Rails, took a bit of googling and piecing together some information. Fortunately I came across <a href="https://riptutorial.com/ruby-on-rails/example/15083/create-an-array-column">this</a> tutorial on adding array columns to your tables. Then it was matter of <a href="https://apidock.com/rails/ActiveRecord/Base/serialize/class">serializing</a> my ingredients and steps attributes by adding the following lines of code to my Recipe class:</p><pre>class Recipe &lt; ActiveRecord::Base</pre><pre>  belongs_to :category</pre><pre>  <strong>serialize :ingredients</strong></pre><pre>  <strong>serialize :steps</strong></pre><pre>end</pre><p>…and voila! The resulting JSON:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mhgnv82lWDCaaqp0XMkLSA.jpeg" /><figcaption>Screen capture by Ian McManus</figcaption></figure><p>One additional challenge I faced was creating two separate controllers for each of my models in my app/controllers directory and having them both run my CRUD related methods for my Recipe and Category classes. Fortunately after a search and some good ole’ trial and error, I came across the <a href="https://learn.co/lessons/sinatra-multiple-controllers">solution</a> provided by learn.co.</p><p>I created two separate controller files, one for categories and one for recipes:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*n3QOA79H4c6g8TVMKwPFIA.jpeg" /><figcaption>Screen capture by Ian McManus</figcaption></figure><p>…then I just had to add the proper code to my config.ru file, loading both controllers. The rest I quote from learn.co:</p><blockquote>Then, we must mount both classes. Only one class can be specified to be run. The other class must be loaded as Middleware.</blockquote><p>You can see the results below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5DEkmnSSauLEUafY9hKSeQ.jpeg" /><figcaption>Screen capture by Ian McManus</figcaption></figure><p><strong>EDIT: In this case, requiring both controllers at the top of my config file was an unnecessary step as all files within my app directory are already required in my configuration’s environment.rb file…</strong></p><p>…and thus I could finally travel to my /recipes and /categories endpoints with ease, keeping my methods and their respective controllers separate and organized.</p><h4>Conclusion</h4><p>Wading through all the syntax and aforementioned “technical jargon” behind Ruby and Active record was easily the most challenging part to wrap my head around. Once I had the know-how, however, utilizing Active Record to get my backend bootstrapped was fairly stress free, aside from the roadblocks I mentioned above. Hopefully these hurdles and the solutions I&#39;ve found will help a fellow newbie coder set up their own Ruby backend using Active Record in the future with relative ease.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ab6b12f30e2f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[My first dive into React]]></title>
            <link>https://medium.com/@ianmcm.89/my-first-dive-into-react-5c02a9f9edd8?source=rss-e3a1b0e55f7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c02a9f9edd8</guid>
            <dc:creator><![CDATA[Ian McManus]]></dc:creator>
            <pubDate>Tue, 11 Jan 2022 05:36:02 GMT</pubDate>
            <atom:updated>2022-01-11T05:36:02.604Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Zu9a6pF_Cv-YV4fd7dNnPg.png" /><figcaption>MGBB App Screenshot by Ian McManus</figcaption></figure><p>For this Flatiron student, it was that time again, the time that cranks my anxiety level higher and makes me don my thinking cap once again...project time. Coming to the end of phase 2, the React phase, I found myself reaching the last ‘lesson’ in the syllabus, the oh so dreaded project criteria.</p><p>Now I’m not saying that I didn’t enjoy the experience or that I didn’t actually learn a good bit about myself and my coding skills along the way, because I certainly did. I only mean that I have historically never stared into the gaping maw of an un-started project looming over me (and my eyes wide with fear) with valor and courage, ready to charge in with my sword and shield in hand. For me, the biggest (and arguably most daunting) question is always…</p><p>“where do I start?….”</p><h4>My Gardener’s Black Book</h4><p>I have, on occasion, dabbled in the gardener’s arts, albeit only somewhat successfully. Have you ever tried to keep a plant alive? It’s like trying to keep a toddler alive, except the toddler shrieks and shrivels up into a dried out husk of its former self at the slightest drop in temperature or change in water level. Too much sun? Dead. Not enough sun? Dead. Too much water? Dead. Not enough water? More death. Soil composition isn&#39;t mixed by a NASA botanist? You get the idea…</p><p>Asking myself what I could create that was also something that I had at least a mild interest in and after some thought, I decided to create My gardener’s Black Book, or MGBB. MGBB would be a way for me to keep track of various plants I&#39;ve tried (whether successfully or unsuccessfully…the jury’s still in on that one) to cultivate from the comfort of my back patio, all neatly organized in my digital plant “black book.”</p><p>To reiterate the readme file, anyone can use the app to search for plants in a database (provided by a JSON backend) and they will find basic information like sunlight exposure requirements, water requirements, seasons to try cultivation and even a short description and an image for reference. Users can also make a post request to the server to add a brand new plant with all the above information via a form coded into the app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*rhd_7K2VbzezFHdXBcVUgg.png" /></figure><h4>What Worked….</h4><p>As a neat freak, one thing I absolutely love about react is its components! Comparing my React project to my vanilla JavaScript project was like night and day. One, an overcrowded mess of code in a single .js file that took some searching and brain trauma to locate this function or that button. The other, a neatly organized (or at least what passes for neat from an inexperienced coding student) framework of many.js files, all with their own little code blocks telling the app what to do.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*jZN2KZruId3PKbwQ91bCzw.png" /></figure><p>I could even separate the CSS into individualized files and import one of those files into a component simply by adding…</p><pre>import “../css/plantForm.css”;</pre><p>…to the top of my component’s .js file. No more scrolling through the Dead Sea Scrolls to find that one class name, just to scroll the other mile and a half to the other end to update an id! Searching through my app to find exactly what I needed suddenly became a breeze with React.</p><p>Another thing I love about React is State.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*vw8wtjQJnJwwWbVs0i8DEg.png" /></figure><p>Combining components and state meant I no longer had to type…</p><pre>element = document.querySelector(selectors);</pre><p>…over and over and over again to find this element or that element and update it in my app. Now, if I wanted to control my form’s input fields, for example, instead of searching for each input with querySelector, I could simply do the initial legwork and import useState() from React…</p><pre>import React, { useState } from “react”;</pre><p>…at the top of my component and then declare my form’s state variable…</p><pre>const [formData, setFormData] = useState({</pre><pre>  name: ‘’,</pre><pre>  image: ‘’,</pre><pre>  sunlight: ‘’,</pre><pre>  water: ‘’,</pre><pre>  season: ‘’,</pre><pre>  description: ‘’,</pre><pre>  likes: 0</pre><pre>});</pre><p>…define a function to update that state on value change…</p><pre>function handleChange(event) {</pre><pre>  setFormData({…formData, [event.target.name]: event.target.value});</pre><pre>}</pre><p>…and finally add my state variable to my input’s value…</p><pre>&lt;input className=”post-input”</pre><pre>  type=”text”</pre><pre>  name=”name”</pre><pre>  placeholder=”Name”</pre><pre>  <strong>value={formData.name}</strong></pre><pre>  onChange={handleChange}</pre><pre>/&gt;</pre><p>…and suddenly I could update my inputs’ values simply by typing in their input fields and then pass my formData state variable to a submit function to get all the updated information in one fell swoop!</p><h4>What I Struggled With…</h4><p>One thing that I admit I still don’t fully understand, is history and the use of routes. It took me much longer than I’d care to admit to figure out that you can’t simply call history.push() from outside your &lt;Router /&gt; unless you want to get an infuriating error along the lines of:</p><p>Uncaught TypeError: Cannot read property ‘push’ of undefined</p><p>I was trying to push history to “/” (my home page) from a &lt;Dashboard /&gt; component I wired up within my app’s &lt;Header /&gt; component, except that I kept getting that same obnoxious error over and over again, banging my head against the metaphorical wall in the process. Not having much experience with React outside of this project and my coursework, I took to the internet to find the solution to my problem.</p><p>After a few forum threads from coders with a similar issue, I found that the overwhelming consensus was thatuseHistory()wasn’t being called within the context of my &lt;Router /&gt;. After digging through my code, I realized that, sure enough, my &lt;Header /&gt; component was outside the context of my &lt;Router /&gt; and thus history had no routes to route to.</p><p>The solution was to simply move my &lt;Router /&gt;up in the context tree. I had placed it in my &lt;App /&gt;component, nestled between my &lt;Header /&gt;and &lt;Footer /&gt;components, the former being the component trying to make use of history. Moving &lt;Router /&gt; up to my index.js component (the highest level on the context tree) allowed me to call useHistory() from any component in my app!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/906/1*6gIpJ7FzPbtXScQ4Bew-Xg.png" /></figure><h4>Conclusion</h4><p>While React at first glance felt like it overcomplicated vanilla JS in a ridiculously discombobulated fashion, I now understand that it was meant to take some of the headache, frustration and repetition out of JS. While there are still aspects of React that I need a deeper understanding of, overall I can now see the beauty and organization react has to offer with a fresher perspective after finishing development of my MGBB app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c02a9f9edd8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Two ‘if…else’ alternatives to use in JavaScript]]></title>
            <link>https://medium.com/@ianmcm.89/two-if-else-alternatives-to-use-in-javascript-3e4c3b51a69d?source=rss-e3a1b0e55f7b------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e4c3b51a69d</guid>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[code-newbie]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[clean-code]]></category>
            <dc:creator><![CDATA[Ian McManus]]></dc:creator>
            <pubDate>Sat, 30 Oct 2021 02:03:54 GMT</pubDate>
            <atom:updated>2021-10-30T02:34:23.063Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*PpgInCl0qHGDzx0c1ap64Q.jpeg" /><figcaption><a href="https://pickupimage.com/free-photos/Stylish-workspace-with-computer/2337510">Stylish Workspace With Computer</a>, by <a href="https://pickupimage.com/portfolio.cfm?uname=pixabay">Pixabay</a>,<strong> </strong>licensed under CC0</figcaption></figure><p>Let’s be honest…writing clean JavaScript code? Not always the easiest skill to wrap one’s head around and certainly a skill that takes time and patience to master. Any programmer, particularly those programmers of the fledgling persuasion (see author’s name), has at some point or another struggled to find the most efficient way to utilize a particular function or block of code.</p><p>The old adage: “keep it <strong>DRY</strong>” i.e. “Don’t Repeat Yourself” <em>sounds</em> easy enough in principle, but it’s execution can often lead the unprepared coder down a figurative foggy backcountry road with multiple forks at two in the morning kind of direction while its pouring rain. What happens when it rains? Our unprepared coder can get <strong>WET</strong> i.e. “We Enjoy Typing.”</p><p>Learning how to code is kind of like learning how to cook. Sure, you can follow the recipe to a ‘T’ and probably reap a seemingly edible pie from the fruits of your labor. After all, anyone can learn how to write a function if they can find the structure and syntax <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions"><strong>online</strong></a>, just as recipes for almost anything imaginable can be found with just the click of a mouse. However, your pie may be edible, <em>maybe</em> even delicious, but it still might feel like there’s something missing in the end. How long did it take you to prep? How many steps were involved? Could you have abstracted out the chopping to your ‘sous chef’ while you tackled making the dough? Was there a better tool to handle all that chopping more quickly and efficiently? All valid questions with many different answers. While I may not have all those answers and this blog post surely won’t make you a clean coder by the time you reach the end, my aim today is to try and help my fellow fledgling coders avoid some repetition and ‘WET’ code in their JavaScript.</p><p>Let’s take a look at the ‘<strong><em>if…else</em></strong>’ statement shall we…</p><h4>The ‘if…else’ Statement Defined</h4><p>If we look at the <a href="https://developer.mozilla.org/">MDN Web Docs</a> take on the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else">if…else</a> statement, we see it defined as such:</p><blockquote>“the <strong>if</strong> statement executes a statement if a specified condition is truthy. If the condition is falsy, another statement can be executed.”</blockquote><p>The if…else statement is simply a conditional statement that does one thing <strong>if</strong> a condition is met (i.e. <em>if</em> our prep work is finished, <em>then</em> bake the pie) <strong>else </strong>another thing is done if it is not (i.e. <em>if</em> the pie needs more prep work, <em>then</em> don’t bake the pie and continue dough prep, chopping, mixing, etc.).</p><p>Using our pie example above, the if…else statement can be written like so:</p><pre>function isPrepped(prepWork) {<br>  if (prepWork === &#39;finished&#39;) {<br>    bakePie();<br>  } else {<br>    return &#39;The pie needs more prep work.&#39;;<br>  }<br>}</pre><p>While this will certainly get the job done and produce a functional result, there are better methods we can use to achieve the same result.</p><h4>The Ternary Operator</h4><p>Let’s take a look at my personal favorite, the <strong><em>ternary operator</em></strong>. Once again referring to MDN resources, we see the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator">ternary operator</a> defined as such:</p><blockquote>“The <strong>conditional (ternary) operator</strong> is the only JavaScript operator that takes three operands: a condition followed by a question mark (?), then an expression to execute if the condition is truthy followed by a colon (:), and finally the expression to execute if the condition is falsy. This operator is frequently used as a shortcut for the if statement.”</blockquote><p>Using the example provided by MDN we see the ternary operator in its purest form:</p><pre>condition ? exprIfTrue : exprIfFalse</pre><p>Now if we apply this syntax to our isPrepped() function above, we can rewrite the functions code like so:</p><pre>prepWork === &#39;finished&#39; ? bakePie() : &#39;the pie needs more prep work&#39;;</pre><p>We’ve taken several lines of code and consolidated them into a single expression with two outcomes. <strong>If</strong> the pie’s prep work is finished, the pie is baked, <strong>else</strong> if it’s not, we get a message declaring that the pie needs more prep work. We’ve utilized the same functionality but in a much cleaner and easier to read way.</p><p>Let’s take a look at one other example, the <strong><em>switch</em></strong> statement…</p><h4><strong>The Switch Statement</strong></h4><p>What if our desired result isn&#39;t as black and white and has multiple conditions? What if we wanted to see the directions for a specific task (chop fruit, make dough, mix filling, etc.) for example? We <em>could</em> define a function like this:</p><pre>function showDirections(task) {<br>  if (task === &#39;chop fruit&#39;) {<br>    return &#39;Dice two cups of desired fruit.&#39;;<br>  } else if (task === &#39;make dough&#39;) {<br>    return &#39;Mix flour, water, sugar and yeast in bowl.&#39;;<br>  } else if (task === &#39;stir filling&#39;) {<br>    return &#39;Stir chocolate and cream till whipped.&#39;;<br>  } else {<br>    return &#39;Please input a valid task.&#39;;<br>  }<br>}</pre><p>While this is totally valid and will achieve the result we want, it utilizes=== strict comparison every time it checks a condition, so our code gets a bit repetitive. There is a simpler method, however.</p><p>The <strong><em>switch</em></strong> statement offers a cleaner solution to solving multiple <strong>cases</strong> than the traditional if…else statement.</p><p>Referring again to MDN we see the switch statement defined as such:</p><blockquote>“The <strong>switch</strong> statement evaluates an expression, matching the expression&#39;s value to a case clause, and executes statements associated with that case, as well as statements in cases that follow the matching case.”</blockquote><p>Using the example provided by MDN, we can see the syntax for the switch statement written like so:</p><pre>switch (expression) {<br>  case value1:<br>    //Statements executed when the<br>    //result of expression matches value1<br>    [break;]<br>  case value2:<br>    //Statements executed when the<br>    //result of expression matches value2<br>    [break;]<br>  ...<br>  case valueN:<br>    //Statements executed when the<br>    //result of expression matches valueN<br>    [break;]<br>  [default:<br>    //Statements executed when none of<br>    //the values match the value of the expression<br>    [break;]]<br>}</pre><p>If we apply this syntax to our showDirections()function above, we can re-write the function utilizing the switch statement and achieve a much cleaner result.</p><pre>function showDirections(task) {<br>  switch (task) {<br>    case &#39;chop fruit&#39;:<br>      return &#39;Dice two cups of desired fruit.&#39;;<br>    case &#39;make dough&#39;:<br>      return &#39;Mix flour, water, sugar and yeast in bowl.&#39;;<br>    case &#39;stir filling&#39;:<br>      return &#39;Stir chocolate and cream till whipped.&#39;;<br>    default:<br>      return &#39;Please input a valid task.&#39;;<br>  }<br>}</pre><p>We’ve achieved the exact same result as before, but we used less repetitive code this time and now have a much more efficient function. The switch statement takes our parameter task and checks each case until the condition is met and returns the statement nested under the condition. If no case matches our task parameter the code executes a message ‘Please input a valid task.’</p><h4>Conclusion</h4><p>Writing clean code takes time to truly understand and master and building a strong toolbelt of different conditional statements can help you streamline your code in the future.</p><p>When it comes to if…then statements, the ternary operator can be used to clean up your code when your desired result satisfies a truthy or falsy condition. The switch statement can be utilized to avoid repetitive code when checking if specific conditions are met on a case by case basis.</p><p>The alternative examples you’ve seen today are only the tip of the proverbial iceberg. As functions get more complex, more complex methods can and will need to be utilized to achieve cleaner, more efficient results from your code. When writing your own code, always ask yourself if there is an easier way to achieve the desired result then the method you are currently using. You’d be surprised what you might find.</p><p>Happy coding!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e4c3b51a69d" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>