<?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 Marshall on Medium]]></title>
        <description><![CDATA[Stories by Ian Marshall on Medium]]></description>
        <link>https://medium.com/@ian-marshall?source=rss-4220b3b0e6fb------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*qqzrqMk3s68Vdb1eWdUNog.jpeg</url>
            <title>Stories by Ian Marshall on Medium</title>
            <link>https://medium.com/@ian-marshall?source=rss-4220b3b0e6fb------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 29 Nov 2026 04:54:54 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ian-marshall/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[Create a minimal hover menu on Shopify with just CSS]]></title>
            <link>https://ian-marshall.medium.com/create-a-minimal-hover-menu-on-shopify-with-just-css-5279c8194df0?source=rss-4220b3b0e6fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/5279c8194df0</guid>
            <category><![CDATA[shopify-development]]></category>
            <category><![CDATA[liquid]]></category>
            <category><![CDATA[no-javascript]]></category>
            <category><![CDATA[navigation-bar]]></category>
            <category><![CDATA[css]]></category>
            <dc:creator><![CDATA[Ian Marshall]]></dc:creator>
            <pubDate>Fri, 17 Feb 2023 23:25:43 GMT</pubDate>
            <atom:updated>2023-02-17T23:28:13.126Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/712/1*3EALYL0E4iYKPhsLbG9m6Q.png" /></figure><p>Shopify gives you a lot of control over how your navigation appears without needing to know any complex code. Their click and drag functionality lets you update navigation throughout your site as well as adding sub-menus. There are many ways to style these elements on the front end, but my favorite performant hover menu can simply use CSS without any Javascript. These instructions will help you create nested menus that reveal sub-menus when you hover over their parent elements and disappear when you navigate elsewhere.</p><p>First, in your Shopify admin, set up menu items in Online Store &gt; Navigation. Here you can either update an existing menu or create a new one — my example will use Main Menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/470/1*QMmxBZdodKN1kgrfJfsbwQ.png" /></figure><p>The first level of elements here will become the first options in the sub-menu: Shop, Media, and Story. Each of these elements has their own destination URL as well as its own sub-menu items. You can add items, click and drag them to elevate them to the first sub-menu or put them further down into another submenu. The margins on the left indicate that the item is an element within the parent menu.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9nHiQI9xcFm3eEF4MBwgqg.png" /></figure><p>Next, we’ll use HTML and Liquid to iterate through this menu structure and populate the HTML element that you’ll see on the front end. Create a file in /sections called “custom-header.liquid” and include the following code:</p><pre>&lt;div class=”menu-banner”&gt;<br>  &lt;h2&gt;Menu&lt;/h2&gt;<br>  &lt;div class=”sub-menu-main”&gt;<br>    &lt;ul class=”sub-menu”&gt;<br>    {% for link in linklists[section.settings.main_menu].links %}<br>      &lt;li class=”{% if link.links != blank %}submenu2-hover {{ link.handle }} {% endif %} {% if link.active %}active{% endif %}” &gt;&lt;a href=”{{ link.url }}”&gt;{{ link.title }}&lt;/a&gt;<br>      {% if link.links != blank %}<br>         &lt;ul class=”sub-menu2 sub-menu2-{{ link.handle }}”&gt;<br>         {% for childlink in link.links %}<br>          &lt;li class=”{% if link.active %}active{% endif %}”&gt;&lt;a href=”{{ childlink.url }}”&gt;{{ childlink.title }}&lt;/a&gt;&lt;/li&gt;<br>        {% endfor %}<br>        &lt;/ul&gt;<br>      {% endif %}<br>       &lt;/li&gt;<br>    {% endfor %}<br>    &lt;/ul&gt;<br>   &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p>The header should also include other items in your navigation, like the merchant’s logo, account navigation, and whatever else you’d like to include. For this example, I’ll just stick with the hover menu. You’ll also need a schema section in this file that will allow you to associate the Main Menu you made in the Shopify admin:</p><pre>{% schema %}<br> {<br>   &quot;name&quot;: &quot;Header&quot;,<br>   &quot;settings&quot;:<br> [<br>   {<br>     &quot;type&quot; : &quot;image_picker&quot;,<br>     &quot;id&quot; : &quot;desktop_logo&quot;,<br>     &quot;label&quot; : &quot;Logo&quot;<br>   },<br>   {<br>     &quot;type&quot; : &quot;link_list&quot;,<br>     &quot;id&quot; : &quot;main_menu&quot;,<br>     &quot;label&quot; : &quot;Main Menu&quot;<br>   },<br>   {<br>     &quot;type&quot; : &quot;image_picker&quot;,<br>     &quot;id&quot; : &quot;menu_background&quot;,<br>     &quot;label&quot; : &quot;Menu Background&quot;<br>   }<br> ]<br> }<br>{% endschema %}</pre><p>This schema gives the merchant control over which menu they are associating with the navigation as well as the logo for the main menu and the background image. You can make these sections very customizable, but, again, I’ll keep it simple and focus on getting the functionality of the hover menu in place.</p><p>The general HTML structure you’ll need to set up this menu includes a header, then some nested elements that will be revealed on hover. The general structure here includes a parent &lt;div&gt; (“menu-banner”), a child &lt;div&gt; (“sub-menu-main”) and then an unordered list &lt;ul&gt; (“sub-menu”) that includes the first set of sub-menu items.</p><p>The general liquid structure iterates through the menu items with two nested for-loops and some if-statements that prevent undesired behavior. The first for-loop takes the link_list produced by the Main Menu we set up in Navigation and creates a list item for each item in the list. Within this for-loop, there are if-statements that add classes if the link is active or being hovered over, which we will build upon with CSS to reveal elements when they are hovered on and hide them again when you navigate away. It’s also worth noting that the handle of each menu item, like “media” or “shop” is added to the &lt;li&gt;’s class, which will be relevant later when styling pseudo-elements.</p><p>Once each of these sub-menu items has been rendered as a &lt;li&gt;, there is an additional if-statement that checks whether these links have links of their own. If the if-statement evaluates as true, another &lt;ul&gt; element is generated with its own for-loop to add in sub-menu items as their own &lt;li&gt;s. This is as far down as my menu goes, but additional for-loops and if-statements could be included to create even more sub-menus.</p><p>Now that the logic and architecture of the hover menu is in place, we need to create some CSS to style this and make it functional. Add this to your dedicated CSS file or between two &lt;style&gt; tags in your custom-header file:</p><pre>.menu-banner {<br>   position: relative; /* The position of the parent element is set to relative */<br>   width: 10%;<br>}<br><br>.menu-banr h2 {<br>   color: #E94917;<br>   font-family: &#39;Area-RegularInktrap&#39;;<br>   font-family: &#39;Area-BoldInktrapExtended&#39;;<br>}<br><br>.sub-menu-main {<br>   position: absolute; /* the position of the first sub-menu is set to absolute */<br>   top: 0px;<br>   left: 80px;<br>   border-left: 1px solid #e94917;<br>   padding-left: 6px;<br>   visibility: hidden; /* the position of the first sub-menu is set to hidden */<br>   opacity: 0;<br>}<br><br>/*<br>The sub-main-meu has visibility set to hidden, but when the menu-banner <br>element is hovered over, the sub-main-menu is set to visible.<br>*/<br><br>.menu-banner:hover .sub-menu-main {<br>    opacity: 1;<br>    visibility: visible;<br>}<br><br>.sub-menu li a {<br>   display: block; /* the links in the sub-menu have display set to block */<br>   width: 200px; /* this width allows you to stay hovering &#39;on&#39; the element <br>                 as you navigate to the right. Without this width, you would <br>                 hover off the element and the sub-menu would disappear.*/<br>}<br><br>/*<br>The ::before here creates a pseudo-element that is the first child of the <br>selected element. In this case we are using it to create the red bar that <br>extends from the sub-menu items to the left to connect the text “Menu” and <br>the child elements<br>*/<br>.sub-menu::before {<br>   content: &#39;&#39;;<br>   position: absolute;<br>   left: -31px;<br>   top: 9px;<br>   width: 26px;<br>   height: 1px;<br>   background-color: #e94917;<br>}<br><br>.sub-menu2 {<br>   position: absolute; /* the links second sub-menu have position set to <br>                       absolute */<br>   left: 97px;<br>   top: 0px;<br>   padding-left: 10px;<br>}<br><br>.sub-menu-main {<br>   position: absolute;<br>   top: 0px;<br>   left: 80px;<br>   border-left: 1px solid #e94917; /* this creates the vertical line to the <br>                                   left of the submenu to show you are looking<br>                                   at a new list of navigation items */<br>   padding-left: 6px;<br>   visibility: hidden;<br>   opacity: 0;<br>}<br><br>/*<br>The ::after here creates a pseudo-element that is the last child of the <br>selected element. In this case we are using it to create the red bar that<br>extends from the menu item to the right<br>*/<br>.sub-menu2::after {<br>   content: &#39;&#39;;<br>   position: absolute;<br>   left: 3px;<br>   top: 0px;<br>   height: 100%;<br>   background-color: #e94917;<br>   width: 1px;<br>}<br><br>/*<br>This transition delay keeps the items visible for a bit after the mouse moves <br>off the menu items so you can navigate between them without them disappearing<br>*/<br>li.submenu2-hover:hover .sub-menu2, .sub-menu-2-shop:hover {<br>   visibility: visible;<br>   transition-delay: 250ms; <br>}<br><br>/*<br>Since the sub-menu items “Shop” and “Media” are different widths, we need <br>custom CSS for each to define the pseudo elements that will stretch out to <br>the right to their respective sub-menus<br>*/<br><br>ul.sub-menu2-shop::before {<br>   content: &#39;&#39;;<br>   position: absolute;<br>   top: 12px;<br>   width: 31px;<br>   height: 1px;<br>   background-color: #e94917;<br>   left: -32px;<br>}<br><br>ul.sub-menu2-media, ul.sub-menu2-shop{<br>   padding-left: 10px;<br>}<br><br>ul.sub-menu2-media{<br>   top: 24px;<br>}<br><br>ul.sub-menu2-media::before {<br>   content: &#39;&#39;;<br>   position: absolute;<br>   top: 8px;<br>   width: 26px;<br>   height: 1px;<br>   background-color: #e94917;<br>   left: -27px;<br>}<br><br><br>.sub-menu2-shop::after, .sub-menu2-media::after {<br>   content: &#39;&#39;;<br>   position: absolute;<br>   left: 3px;<br>   top: 0px;<br>   height: 100%;<br>   background-color: #e94917;<br>   width: 1px;<br>}<br><br>/* This styling makes the links red, then grey on hover */<br>.sub-menu2 li.active&gt;a, .sub-menu li.active&gt;a {<br>   color: #e94917;<br>}<br>.sub-menu2 li.active&gt;a:hover, .sub-menu li.active&gt;a:hover {<br>   color: #808080;<br>}</pre><p>Much of the CSS that deals with top, bottom, left, and right as well as the padding is idiosyncratic to the menu you are working with — you want to make sure the lists of elements and the pseudo elements are all properly sized and spaced, so you will have to play around with these values to make sure that the menu is portioned the way you expect.</p><p>The final result is a sleek, minimal menu that can be easily customized to add new sub-menus. Best of all, since this doesn’t require any Javascript, your storefront will not be slowed down by any additional scripts.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5279c8194df0" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How not to ace the debugging interview]]></title>
            <link>https://ian-marshall.medium.com/how-not-to-ace-the-debugging-interview-c2f77eed3f0f?source=rss-4220b3b0e6fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/c2f77eed3f0f</guid>
            <dc:creator><![CDATA[Ian Marshall]]></dc:creator>
            <pubDate>Thu, 09 Jun 2022 17:24:42 GMT</pubDate>
            <atom:updated>2022-06-09T17:30:52.012Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/679/1*xbokhO7gxYtjIU4CBN2JPA.jpeg" /></figure><p>For better or worse, the majority of programming is not spinning up a fresh application from scratch, but trudging through code written by others to track down unexpected behaviors, add new features, and repair any incorrect logic. Recently, I completed a two part technical interview for a support engineer position that required me to create a basic Ruby app from scratch in part one and debug a similar app in part two: while part one went well enough, I struggled to recreate the same success in part two, despite the similarities between the goals of the projects.</p><p>More often than not, the goals of technical interviews are not to wow the interviewer with your encyclopedic knowledge of every shortcut and piece of syntactic sugar you can invoke on the fly, but to face challenges where you don’t have all the answers. The way that you approach questions where you don’t have an answer is much more telling of the rhythm of how you work: do you jump around and try to reason out why things aren’t working by reading the code line-by-line? Or do you work through the problem methodically, testing the behavior of individual blocks of code? Everyone should strive for the second scenario, but having recently (briefly) forgotten my best practices, I wanted to share some tips for how to put your best foot forward for the debugging interview.</p><p><strong>Start small and move to bigger problems</strong></p><p>It’s tempting to look at the big picture when working on a coding problem — why isn’t the output exactly the way it should be? You can always start here, but eventually you will need to drill down to the ancillary functions to check that they’re working the way you expect. For example, in my interview I was debugging a simple piece of software that dealt with stock trades. If the overall goal of a piece of software is to take a series of inputs (like initializing stocks, changing the value of stocks, trading stocks, and so on) and output a summary of everything that’s happened (total spend, total earnings, return on investment, etc), you should always start with how the smallest pieces of information are being interpreted. If there is a single function for calculating a percent change, for example, start there by including a statement to print out the results to make sure that the building blocks of your application are behaving as expected. <em>Once you’re confident all of the small pieces are working well, you can move onto bigger functions that call on each of those smaller functions.</em></p><p><strong>Use your own inputs</strong></p><p>While a block of code can run many different functions, you can always simplify the problem by changing your inputs. Try simplifying the inputs to test a specific function — like instantiating a user — rather than running every single part of the application to test just one component. <em>If the values that are being inputted are creating the desired output, try it with a slightly different value to make sure that you don’t have any blind spots in your thinking.</em></p><p><strong>Punch the biggest bully in the yard</strong></p><p>One of my biggest mistakes in my recent debugging interview was to focus on simple functions that I was familiar with (like the value of stocks going up by some percent) rather than jumping into totally new challenges. I was intimidated by a new question and thought that I could get more points by solving a handful of (seemingly) easier questions in the same amount of time. While this is a good strategy for a multiple choice test, you might actually earn more points (and understand the problems with the code you are debugging faster) if you jump in the deep end. For me, this was figuring out how an unfamiliar feature, splitting a stock by increasing the number of shares outstanding and lowering the individual value of each share, was supposed to work. By the time I started working on this specific question I realized that I was running out of time, so I felt rushed and anxious. <em>Once I started digging in, I realized that the issues with the code block were more obvious than I had anticipated, and I was able to add some bonus logic that fulfilled all of the desired outcomes of the function.</em> If I had started with this problem first, it would have become a known and trusted component of a larger program rather than a black box to avoid until the last second.</p><p><strong>Google early and often</strong></p><p>You are almost always allowed to google things you’re unfamiliar with. Searching for answers is an essential part of being an engineer, and while certain things are more embarrassing to google than others, if you don’t know the answer to something you should definitely not hesitate to find it out! Some of the things i googled during this recent interview include:</p><ul><li>what does “/=” mean in ruby</li><li>how does splitting a stock work</li><li>how does ruby hash use each</li><li>ruby [0..-2]</li></ul><p>Some of these searches might be evidence of temporary amnesia — I know (I really do!) that in Ruby you need to include parentheses when you iterate with each() — but in the moment, you might not remember every single thing you’ve ever learned. <em>Getting the answers to the exact problems you’re working on is more valuable than guessing different syntax in front of your audience to try and get the result you need.</em></p><p><strong>Think out loud (really)</strong></p><p>Almost always, this is an explicit instruction for technical interviews: talk through your reasoning and what you’re trying to do so your interviewer can learn more about how you approach a problem. Even though it’s a direct request from your interviewer, you might forget from time to time to explain exactly why you’re doing something in a certain way. <em>If it helps, think of this as </em><a href="https://en.wikipedia.org/wiki/Rubber_duck_debugging"><em>rubber duck debugging</em></a><em> — by explaining things as if you were talking to yourself (or an inanimate object), you might even hear yourself explaining the solution.</em></p><p><strong>Remember: you do this all the time</strong></p><p>I was tempted to include this piece of advice first, but it’s too good of a final takeaway: <em>if you made it this far, you might know what you’re doing</em>. You de-bug your own code all the time, and have your own strategies in place to work efficiently. Just because you’re working on a shared IDE under the watchful eyes of two senior engineers following your every move doesn’t mean you should do anything differently than what you normally do. You might even ask them “what’s the best way for me to check this individual function?” in case it isn’t obvious. Sometimes there’s a “run code” button that you can miss, or if there’s a special CLI command you aren’t familiar with, it will always be better to ask those questions at the beginning before you spend too much time just guessing what the outputs might be. For me, the biggest hurdle was remembering that I could just as easily throw a puts &lt;variable&gt; into a code block to check the value of individual variables — something I do all the time, but forgot to do because of the unfamiliar setting.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c2f77eed3f0f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A beginners guide to Shopify Themekit and Schema]]></title>
            <link>https://ian-marshall.medium.com/a-beginners-guide-to-shopify-themekit-and-schema-3a7689c4fc84?source=rss-4220b3b0e6fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/3a7689c4fc84</guid>
            <category><![CDATA[shopify-development]]></category>
            <category><![CDATA[schema]]></category>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[shopify-theme]]></category>
            <category><![CDATA[theme-kit]]></category>
            <dc:creator><![CDATA[Ian Marshall]]></dc:creator>
            <pubDate>Fri, 28 Jan 2022 22:01:32 GMT</pubDate>
            <atom:updated>2022-02-01T16:09:31.278Z</atom:updated>
            <content:encoded><![CDATA[<h3>A beginner’s guide to Shopify Themekit and Schema</h3><figure><img alt="shopify developers banner" src="https://cdn-images-1.medium.com/max/1000/1*4S1FUg5X9-S_jSKIpx02VQ.jpeg" /></figure><p>I began to learn to code during lockdown in 2020 and since then I have relied on the kindness of strangers to share their own solutions, insights, and hacks when I get stuck. Now in my first dev job, I find not much has changed, and googling specific error messages is synonymous with “engineering”. While Shopify has <em>a lot</em> of information for developers, in my experience their documentation is verbose to the point of redundancy. Why are there so many different pages, and no examples? In the spirit of paying it forward, I’d like to share some of the guidance that I would have liked when I began front end development using Shopify Themekit.</p><p><a href="https://shopify.dev/themes/tools/theme-kit">Themekit</a> allows you to duplicate your website’s existing design into an unpublished version that you can modify without affecting the deployed version visible to your clients. Rather than pushing your changes to Github, with commands like $ themewatch you can see your updates in real time*.</p><p><em>*Web development through Themekit still requires hard reloads of your page to see changes, but this is still less steps than pushing your changes to a repo manually.</em></p><h3>Part 1 — Setting up Themekit in your local environment</h3><p>I used Homebrew to set up themes on my local environment with these commands:</p><p>$ brew tap shopify/shopify</p><p>$ brew install themekit</p><p>Once Themekit is installed, you can start working on modifying a theme through your text editor, like VSCode, rather than a browser window. Create a folder for your files, `$ cd` in, and run this command:</p><p>$ theme get --password=&lt;password --store=&lt;store&gt; --themeid=&lt;theme id&gt;</p><ul><li>Find the &lt;password&gt; on Shopify — log into the specific client, then navigate to Apps &gt; Manage private apps (bottom of the page) &gt; ThemeKit (click in) &gt; copy password*<br><em>*Since publishing this in January 2022, the Manage private apps link has moved from the bottom of the app page in Shopify. Now, you can add the </em><a href="https://apps.shopify.com/theme-kit-access?shpxid=b6033f5f-BD29-4449-CD7D-138599561407"><em>Theme Kit Access</em></a><em> app and the store admin should receive the Theme Kit password in their email. More info from Shopify’s official documentation </em><a href="https://shopify.dev/themes/tools/theme-kit/getting-started#get-theme-kit-password"><em>here</em></a><em>.</em></li><li>Find the &lt;store&gt; in the url in your browser (should be similar to store-name.myshopify.com)</li><li>Find the &lt;theme id&gt; on Shopify — navigate to Online Store &gt; Themes &gt; choose theme &gt; Edit code &gt; copy theme id from URL (should be similar to 121276235841, a number at the end of the URL)</li></ul><p>Finally, run $ code . to open the theme in your text editor and then $ theme watch so that Shopify will automatically update the theme. Any errors in your .liquid files will prevent the code from syncing, which also provides another layer of quality assurance — the theme visible on your browser will stop updating before it breaks. To turn off themewatch, simply run ctrl + c</p><h3>Pt 2 — Schemas and adding Functionality</h3><p>In addition to modifying the front end of your site, you can create settings in your front end code that are accessible to the admin of your Shopify account. This is helpful if you are working for a client that doesn’t have their own development team and needs to manage content or switch between different versions of a page without a developer’s assistance. <strong>Broadly, you will do this by creating fields in the Shopify backend that the client can control. You’ll create a checkbox, a text box, or any number of tools that allows them to toggle and update the look and feel of the front of the website.</strong></p><p>The workflow for using schemas to add functionality is</p><ol><li>updating the schema to create the fields that they see in the back end and</li><li>updating the relevant .liquid file to include conditional statements in <a href="https://shopify.github.io/liquid/">Liquid</a></li></ol><p>There’s more than one right way to use schemas, but one of the simplest and most powerful is adding an if / else operator in a &lt;div&gt; or other element so the styling turns on and off.</p><p>In your theme, navigate to /config/settings_schema.json to find the available fields for different settings in the Theme that show up on the Shopify backend. For example, this might be the JSON for the header of your Shopify site:</p><pre> {</pre><pre>   “name”: “Header”,</pre><pre>   “settings”: [<br>     {</pre><pre>       “type”: “header”,</pre><pre>       “content”: “Header Styling”</pre><pre>     },</pre><pre>     {</pre><pre>       “type”: “checkbox”,</pre><pre>       “id”: “header_gradient”,</pre><pre>       “label”: “Apply gradient to transparent header”,</pre><pre>       “default”: false</pre><pre>     },</pre><pre>     {</pre><pre>       “type”: “checkbox”,</pre><pre>       “id”: “nav_fonts_weight”,</pre><pre>       “label”: “Make header fonts bold”,</pre><pre>       “default”: false</pre><pre>     },</pre><pre>     {</pre><pre>        “type”: “header”,</pre><pre>        “content”: “Logo”</pre><pre>     },</pre><pre>     {</pre><pre>        “type”: “checkbox”,</pre><pre>        “id”: “logo_use_image”,</pre><pre>        “label”: “Use custom logo”</pre><pre>     },</pre><pre>     {</pre><pre>        “type”: “checkbox”,</pre><pre>        “id”: “meganavimage”,</pre><pre>        “label”: “Use MegaNav Image”</pre><pre>     },</pre><pre>     {</pre><pre>        “type”: “image”,</pre><pre>        “id”: “logo.png”,</pre><pre>        “label”: “Custom logo”,</pre><pre>        “max-width”: 450,</pre><pre>        “max-height”: 200,</pre><pre>        “info”: “450 x 200px .png”</pre><pre>     },</pre><pre>     {</pre><pre>        “type”: “text”,</pre><pre>        “id”: “logo_max_width”,</pre><pre>        “label”: “Max logo width”,</pre><pre>        “default”: “450”,</pre><pre>        “info”: “Defined in pixels. Do not add the ‘px’ unit.”</pre><pre>     },</pre><pre>     {</pre><pre>        “type”: “header”,</pre><pre>        “content”: “Favicon”</pre><pre>     },</pre><pre>     {</pre><pre>        “type”: “checkbox”,</pre><pre>        “id”: “favicon_enable”,</pre><pre>        “label”: “Use custom icon”</pre><pre>     },</pre><pre>     {</pre><pre>        “type”: “image”,</pre><pre>        “id”: “favicon.png”,</pre><pre>        “label”: “Icon”,</pre><pre>        “max-width”: 32,</pre><pre>        “max-height”: 32,</pre><pre>        “info”: “32 x 32px .png required”</pre><pre>     }</pre><pre>   ]</pre><pre>}</pre><p>This JSON object includes a number of important parameters:</p><ul><li><strong>type</strong> — this corresponds to what tool will show up on the Shopify backend. If you set it to “checkbox” there will be a checkbox. If you set it to “header” it will be a header for the settings. And so on.</li><li><strong>content</strong> — for “type”:”header” specifically, this corresponds to what the header will say in the settings.</li><li><strong>id</strong> — this corresponds to how you reference this setting in the .liquid file. If you name it “header_gradient” then you will reference it in the liquid file with settings.header_gradient</li><li><strong>label</strong> — this corresponds with the name of the field on the Shopify backend. if you name it “Header Gradient” it will show up as Header Gradient.</li><li><strong>default</strong> — specifically for checkbox, if you set the default to false (not “false”) then the box will be unchecked by default. If you set it to true, it will be checked by default</li><li><strong>info</strong> — this corresponds with the subtitle of the field on the Shopify backend. If you write “Click to apply gradient/vignette to transparent header” then under the checkbox on the backend you will see the same text underneath. <em>This is good for instructions, file requirements, or more explanation if the title of the field is at all unclear.</em></li></ul><p>To see the changes you’ve made in settings.schema.json in the Shopify admin, navigate to Themes &gt; the theme you’re working on, and click on Customize, then Theme Settings. Click into the section you’re working on and you should see the changes from your settings.schema.json file show up on the left hand navigation. Make sure you reload after any changes to the .json file to see the schema reflect in the admin!</p><p>In a corresponding <a href="https://shopify.dev/themes/architecture/sections">section</a> you can add in the functionality that will make the settings you’re adding to the backend actually work. In these examples, the setting id is “my_setting”:</p><p>wrap whatever block of code that is meant to change in {% if settings.my_setting %} and {% endif %}. This means that if my_setting is checked (true) then the block is executed. Here’s an example of code from a .liquid file that corresponds to the header JSON schema above:</p><pre>&lt;div class=”header-sticky-wrap {% if template contains ‘index’ %}header-transparent{%endif%}” {% if settings.header_gradient and template contains ‘index’ %} style=”background-image: linear-gradient(to top, transparent, #373737);” {% endif %} &gt;</pre><p>Here, if the box is check on the back end, then if settings.header_gradient will evaluate to true and the style tag in the element will turn on. This is huge! You can create custom settings that anyone can modify, not just developers.</p><p>It’s worth noting that could also use the same conditional logic with class names, id names, or entire elements. The flexibility of these tools is a double edged sword: on the one hand, anything is possible, but this also means that there are a lot of opportunities for personal idiosyncrasies in styling from developer to developer. It’s important to use naming conventions that other developers (as well as future you) will recognize.</p><p>I hope this is a helpful reference for any developers new to working on Shopify Themekit and schemas! I also hope that I can continue to build on this series as I learn more about the ins and outs of Shopify frontend development. To that end: please let me know if you have any questions or ideas about features that I can explore.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3a7689c4fc84" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The simplest version of the internet]]></title>
            <link>https://ian-marshall.medium.com/the-simplest-version-of-the-internet-52cfc5eaf200?source=rss-4220b3b0e6fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/52cfc5eaf200</guid>
            <dc:creator><![CDATA[Ian Marshall]]></dc:creator>
            <pubDate>Thu, 12 Aug 2021 18:59:49 GMT</pubDate>
            <atom:updated>2021-08-12T18:59:49.642Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*6RfNN-jHsURIIvlj.jpg" /></figure><p>In a recent interview for an engineering position I was asked a very broad-reaching question: how does the internet work? There are many different answers to this question, depending on how granular you’d like to get, so I wanted to share the simplest version I can.</p><p>At its most basic, the internet would consist of two computers: a <em>client</em>, and a <em>server</em>. Let’s say we’re using a cell phone to check the menu at a restaurant — in this example, the cell phone would be the client, and the server would be whatever computer is hosting the menu. Even in this very simple example, there are a handful of steps: you enter a URL in your phone’s browser, the browser looks up the IP address for the domain name, the browser sends an HTTP request, and then the server sends back an HTTP response. In most cases, the browser would then send additional requests for objects in HTML, like image media, CSS, and JavaScript through the same initial steps.</p><p>To take a closer look at these steps, we should talk about routers. In our example, when we visit the restaurant’s website on our phone, we’re requesting information that is delivered by routers. The core of the internet are routers that move information in <em>packets</em>. If the information we’re interested in is especially large, it would be broken up into several packets. The routers each have a table of numbers to outbound links, which are used to route the packages based on the destination address. You might imagine a packet of information like a letter in an envelope, with a destination address and a return address. When these packets go on their journey, they make several stops, and each subjourney is called a <em>hop</em>. A packet would hop from your laptop over your wifi to a modem box, and then from there to Verizon or AT&amp;T’s bigger router, and then further out in the world.</p><p>So far this might not be that surprising — information is stored somewhere and retrieved when it’s requested. The model for this system is called TC/ICP (Transport Control Protocol / Internet Protocol), which is made up of four layers: Link, Internetwork, Transport, and Application.</p><p>The <strong>Link</strong> layer is responsible for connecting a computer to its local network. In our example, the cell phone is the computer and the local network would be the cell network or WiFi. The data moves in a single hop from the cell phone to its first router, which is also called a <em>gateway</em> or a <em>base station</em>. Any base station uses link layer technology to connect to the next router. In our example, that means the radio frequencies used to transmit data and how that data will be encoded in the radio signal. Since every computer receives packets broadcasted by the station and by nearby computers, the packet has information specific to the computer’s own wifi radio — what’s called a <em>MAC address.</em> Your computer’s MAC address is unique, and remains the same for the life of the radio.</p><p>Now that our phone has made it to the base station, the next layer after Link is <strong>Internetwork</strong>. Our packet is in the router and includes attributes like its <em>source address</em> and its <em>destination address</em> (like the return address and destination address on an envelope). These attributes are both called <em>IP addresses</em> and are given to every computer based on where the computer is connected to the internet. If you drive a town over, your cell phone’s IP address would change, but the MAC address will always be the same.</p><p>IP addressing allows for routers to build <em>routing tables</em> to get packets to their correct destinations, but because information is broken up into packets they may arrive out of order, or even mishandled and lost. For example, a loop can form where information is passed in a circle and never arrives at its destination, so to solve this problem packets have another attribute called <em>TTL</em> or Time To Live. This number counts down with every hop, and the packet expires after the countdown reaches zero.</p><p>With the risk of our packets arriving out of order or even dying in transit, we’ve arrived at the <strong>Transport</strong> layer. The transport layer solves these two problems by interpreting each packet’s “header”, which includes data about the overall message, including its total length or the number of packets. In the destination computer, a message is reconstructed using these attributes and it can be determined whether it has received all of the packets and which are missing. While waiting for the destination computer to send acknowledgement that the packet has been received, the source computer will temporarily store a copy of each of the parts of the original message that have been sent so far. This means the source computer will send information, wait for acknowledgement from the destination computer, and then continue to send packets.</p><p>This brings us to the <strong>Application</strong> layer. Web applications can broadly be split into two categories: clients and servers. Both need a protocol that describes how they will exchange messages, and HTTPS (hyper text transfer protocol secure) is one such protocol. HTTPS works through requests — we made a request on our phone when we entered the URL of the restaurant menu, and the server that holds the menu made a request back. The most common request header (and the one happening here) is GET, which displays information, but others like PUT and PATCH modify information and DELETE deletes a specific resource. These request headers are sometimes referred to as HTTP verbs. Once your browser begins rendering the HTML, it places additional requests for media like CSS, JavaScript, and images. Each request follows the same request and response cycle, often to different destination addresses — for example, images might be hosted on a separate server than fonts, and so on.</p><p>As complex as this simple explanation may be, there’s always more complexity if you’re interested (for example, look into encryption with HTTPS or into the OSI / Open System Interconnection model, an alternate network design model to TCP/IP). Broadly, this explanation should at least show the underlying pattern at play whenever you open a browser on your phone or computer.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=52cfc5eaf200" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Defining components with const vs class in React]]></title>
            <link>https://ian-marshall.medium.com/defining-components-with-const-vs-class-in-react-bf43bb7cae74?source=rss-4220b3b0e6fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/bf43bb7cae74</guid>
            <dc:creator><![CDATA[Ian Marshall]]></dc:creator>
            <pubDate>Tue, 25 May 2021 23:58:07 GMT</pubDate>
            <atom:updated>2021-05-25T23:58:07.487Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/626/0*L0BMfl6ZKwNza0Sj.jpg" /></figure><p>While learning React (or any new coding language) I find myself defaulting to following a recipe — I look for another example of a component or function that works, and I use that example to guide my own decision making. I like the analogy of calling this “following the recipe” because it’s very similar to cooking: I’m not going to wake up one day to discover myself transformed into a French chef, but I might learn how to create components or a dish here and there, and one day be able to use those experiences to create something of my own. Without knowing these basics, it’s difficult to believe you’d ever be able to build up to creating a functioning application, though there are often helpful guides along the way.</p><p>Following some such guides, I still find myself confused about certain conventions, specifically those surrounding when we as developers should use <strong>const</strong> or <strong>class</strong> when defining components in React. Asking my peers and instructors at Flatiron, I found a lot of ambivalence surrounding the topic: some say that using const to create functional components gives a performance boost, but there are other tradeoffs that make these patterns less desirable depending on what you want your component to do. I’m hoping that by explaining some examples of my own, I can offer guidance to anyone who is trying to decide between using const or class to define components in their React App.</p><p>Very simply, the biggest difference between using const or class when defining a component is <strong>state</strong>. is changeable data in a component. Unlike props, state can change during the component’s life. It provides us with a way to update and maintain data within a component that doesn’t rely on a parent component to pass down updated information in the form of props, which can get very complicated depending on how many components your app contains. Class components have state, but components defined with const (also known as Functional components) do not.</p><p>Here’s an example of a class component:</p><pre>import React, { Component } from ‘react’</pre><pre>class BigComponent extends Component {</pre><pre>   state = {</pre><pre>      someValue: “this is a class component.”</pre><pre>   }</pre><pre>   render() {</pre><pre>      return (</pre><pre>         &lt;div&gt; I’m the return! {this.state.someValue}&lt;/div&gt;</pre><pre>      )</pre><pre>   }</pre><pre>}</pre><p>Class components allow you to take advantage of lifecycle methods, like componentDidMount(), which allow you to call functions at different points in the component’s lifecycle. This is especially helpful if you want to perform a fetch request, sanitize props when a component updates, or clean up data before a component un-mounts — any function that should be triggered by an aspect of the component’s lifecycle.</p><p>Class components are also a JavaScript class, which means you’re creating <em>instances</em> of that class when you deploy class components. This is object-oriented programming: React expects your class component to return a React element from its render function, though this rendering does not add up to much of a difference in time between class components or functional components.</p><p>As it happens, class components in React came <em>after</em> functional components, aka components defined with <strong>const</strong>. Functional components are stateless, which means you can’t employ such helpful tools as referencing this.state, like I did above when accessing “this is a class component” with this.state.someValue. It also means that you can’t use lifecycle methods, though you can use lifecycle <em>hooks</em>, which operate very similarly. Here’s an example with useEffect:</p><pre>Import React, { useEffect } from ‘react’;</pre><pre>const AnotherComponent = ({ someElement }) =&gt; {</pre><pre>   useEffect(() =&gt; {</pre><pre>      console.log(“I will log when the value of ‘someElement’ changes”);</pre><pre>   }, [someElement]);</pre><pre>   return &lt;div&gt;I’m the return! &lt;/div&gt;</pre><pre>}</pre><p>In this example, the useEffect hook will evaluate when the value of someElement changes. If we were to write this with class components, it would require a bit more logic to define the same behavior:</p><pre>import React, { Component } from ‘react’;</pre><pre>class BigComponent extends Component {</pre><pre>   componentDidUpdate(prevProps) {</pre><pre>      if (this.props.someElement !== prevProps.someElement) {</pre><pre>         console.log(“I will log when the value of ‘someElement’ changes”);</pre><pre>      }</pre><pre>   }</pre><pre>   render() {</pre><pre>      return &lt;div&gt; I’m the return! &lt;/div&gt;</pre><pre>   }</pre><pre>}</pre><p>There are <a href="https://blog.carbonfive.com/replacing-component-lifecycle-methods-with-react-hooks/#:~:text=When%20writing%20React%20components%2C%20we,before%20the%20component%20unmounts%2C%20etc.">a lot of other examples</a> of how to use either lifecycle methods in class components or lifecycle hooks in functional components, which accounts for some of the ambivalence surrounding which people prefer to use — if you can accomplish the same functionality in either, why worry about making the wrong choice? One of the biggest differences when writing the code is that class components and lifecycle methods require a bit more imperative programming — for example, if you have any setup like componentDidMount, it mandates you would need componentWillUnmount to clean up. Functional components and their lifecycle hooks have no such necessity since the logic of mounting and un-mounting is included in the function scope.</p><p>So, finally, some advice: as a hard and fast rule, since functional components don’t have state (or internal variables), they’re ideal for simple components, like buttons: you can pass any callback function through props like so:</p><pre>const Button = (props) =&gt; (</pre><pre>   &lt;button onClick={props.handleClick}&gt; {props.buttonLabel}&gt;</pre><pre>   &lt;/button&gt;</pre><pre>)</pre><p>In contrast, when any component that relies on Redux, internal react state, or needs data that can’t be passed with a prop, you should use a class component. Another good use is when considering user interaction (does this block need to expand? you’ll probably rely on state to inform that behavior).</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bf43bb7cae74" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leveraging nested routes in fetch requests]]></title>
            <link>https://ian-marshall.medium.com/leveraging-nested-routes-in-fetch-requests-c53124d2413d?source=rss-4220b3b0e6fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/c53124d2413d</guid>
            <dc:creator><![CDATA[Ian Marshall]]></dc:creator>
            <pubDate>Mon, 19 Apr 2021 22:29:03 GMT</pubDate>
            <atom:updated>2021-04-19T22:29:03.352Z</atom:updated>
            <content:encoded><![CDATA[<p>Creating my first application with a Javascript front end and Ruby on Rails backend provided plenty of challenges, from small things like mixing up syntax when switching between languages to bigger decision making, like choosing when to create methods and functions in Javascript and when to use Ruby. My biggest challenge was figuring out how to leverage methods in both languages to create an efficient application. I built my project (a simple chat app called Gabbo) vertically, which meant (in practice) tying all of the pieces together without giving too much thought to more nuanced details like querying exactly which chats I should be rendering, when I should be filtering, and what the most efficient strategies might be along the way.</p><p>When refactoring, I learned a lot about how to fetch messages from my database that only pertain to the current user. My application consists of three models: a User class (has many chats), a Chat class (belongs to many users, has many Messages) and a Message class (belongs to a user, belongs to a chat). My refactor focused on three areas of my app: my routes, my Chats controller, and my ChatsApi.js file, which encapsulated the logic that made fetch requests to create and show chats between users.</p><p>Originally, when rendering chats I made my fetch request to all chats (‘<a href="https://localhost3000/chats">https://localhost3000/chats</a>), then sorted the chats using Javascript to only display those that contain the user_id of the current user. This made sense while building the application because the current user is only defined on the front end, but if the app were to grow to hundreds or thousands (millions?) of users, this sorting step would become increasingly taxing.</p><p>To make fetch requests that only return chats that include the current user, the first step is to have nested routes — from my routes.rb file:</p><pre>Rails.application.routes.draw do<br> # root ‘index’<br> resources :users, only: [:index, :show, :create] do<br>    resources :chats, only: [:index, :show, :create] do<br>       resources :messages, only: [:index, :create]<br>       end<br>    end<br>end</pre><p>Nested routes reflect a certain logic — messages belong to chats, and chats belong to users, so it would make sense to navigate to a specific chat in a route like /users/1/chats/2/messages, where the 1 and 2 represent the ids associated with a specific user and a specific chat, respectively.</p><p>These routes should (perhaps obviously?) be reflected in your fetch requests. In case you are refactoring your routes rather than beginning with nested routes from scratch, it’s worth noting that changing your routes to be nested will affect all of your fetch requests related to users, chats, and messages. Here’s my getChats() function from my ChatsApi.js file:</p><pre>static baseUrl = `<a href="http://localhost:3000/api/v1/users/%60">http://localhost:3000/api/v1/users/`</a></pre><pre>static getChats(){<br>   const user_id = User.setCurrentUser().id // this method returns the current user object<br>    fetch(this.baseUrl+`${user_id}/chats`)<br>    .then(r =&gt; r.json())<br>    .then(json =&gt; {<br>       json[“data”].forEach(element =&gt; {<br>          const chatWindow = new Chat({id: element.id, <br>          sender: element.attributes.sender, <br>          recipient: element.attributes.recipient, <br>          messages: element.attributes.messages})<br>       chatWindow.render();<br>       chatWindow.attachToDom();<br>       Chat.getMessages(chatWindow);<br>       })<br>    })<br> }</pre><p>Notice that the baseUrl I define is for users rather than chats. Because chats belong to users, I use interpolation to incorporate the current user’s ID, which means that the JSON returned from the fetch request will only include those chats that feature the current user.</p><p>One more important ingredient in making sure these fetch requests work is to white list the user_id in your params — from my ChatsApi.js:</p><pre>class Api::V1::ChatsController &lt; ApplicationController</pre><pre>   def index <br>      user_id = params[:user_id].to_i<br>      sender_chats = Chat.all.select { <br>         |chat| chat.sender_id == user_id}<br>      recipient_chats = Chat.all.select { <br>         |chat| chat.recipient_id == user_id}<br>      all_chats = (sender_chats+recipient_chats).uniq<br>      options = {<br>      include: [:messages]<br>      }<br>      render json: ChatSerializer.new(all_chats, options)<br>   end</pre><pre>private</pre><pre>  def chat_params<br>     params.require(:chat).permit(:sender_id, :recipient_id, :user_id)<br>  end</pre><pre>end</pre><p>Here, the index action converts the user_id to an integer because my setCurrentUser() method returns a string value. Next, this value is passed on to define the sender_chats and recipient_chats arrays, which are combined into an all_chats array.</p><p>By restricting the JSON that’s returned from the server to just the chats that include the current user, I greatly reduce the amount of sorting that has to be performed by the front end functionality of my application and allow for separation of concerns — sorting the data is done by the portions of the application that are best sorted for interacting with the database. Even though my application is small and rendering chats is not a particularly taxing or time consuming operation, maintaining this separation of concerns would make a huge difference in performance if the application were to scale to thousands or millions of users.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/612/0*m5EIsDJwRksSjdLK" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c53124d2413d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[innerHTML vs append with Event Listeners]]></title>
            <link>https://ian-marshall.medium.com/innerhtml-vs-append-with-event-listeners-b13cba10cdf8?source=rss-4220b3b0e6fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/b13cba10cdf8</guid>
            <dc:creator><![CDATA[Ian Marshall]]></dc:creator>
            <pubDate>Mon, 12 Apr 2021 16:34:23 GMT</pubDate>
            <atom:updated>2021-04-12T16:34:23.839Z</atom:updated>
            <content:encoded><![CDATA[<p>When creating my first JavaScript / Rails API application I found myself creating many (simple) methods for the first time, like manipulating the DOM and sending fetch requests to the server. Of all the simple methods that I struggled with, adding event listeners was oddly the most vexing.</p><p>I built a chat app with a ruby User class, Chat class, and Message class: users have many chats, chats have many users (specifically, two), and users and chats have many messages. This portion of the chat app I was building includes three main functions — getChats(), which fetches chat objects from the database; renderChats(), which confirms the chat includes the current user and creates the chatMarkup; and addEvents(), which adds an event listener to the chat button. There’s also getMessages(), which adds all of the existing messages to each chat, but it’s not as important in the following example. Here’s my original, buggy code:</p><pre>function getChats() {</pre><pre>   clearChats()</pre><pre>   fetch(chatsEndPoint)</pre><pre>   .then(response =&gt; response.json())</pre><pre>   .then(chats =&gt; {</pre><pre>      chats.data.forEach(chat =&gt; {</pre><pre>         renderChat(chat);</pre><pre>      });</pre><pre>   })</pre><pre>}<br></pre><pre>function renderChat(chat){</pre><pre>   if ((chat.attributes.sender_id.toString() === currentUserId.toString()) || (chat.attributes.recipient_id.toString() === currentUserId.toString())){</pre><pre>      const chatMarkup =`</pre><pre>         &lt;div class = &quot;chat&quot;, id = &quot;chat-${chat.id}&quot;&gt;</pre><pre>            &lt;h3&gt;Chat between ${chat.attributes.recipient.name} and ${chat.attributes.sender.name}&lt;/h3&gt;</pre><pre>            &lt;div class = &quot;messages&quot;&gt; &lt;/div&gt;</pre><pre>         &lt;form method=&quot;post&quot; class = &quot;chat-form-chat-${chat.id}&quot;&gt;</pre><pre>            &lt;input class=&quot;message-compose-area&quot; id = &quot;chat-form-chat-${chat.id}&quot; type=&quot;text&quot; name=&quot;body&quot;&gt;&lt;/input&gt;</pre><pre>            &lt;input type=&quot;submit&quot; value=&quot;Gab&quot; class=&quot;send-message&quot; id= &quot;gab-button-${chat.id}&quot;&gt;  &lt;/input&gt;</pre><pre>         &lt;/form&gt;</pre><pre>         &lt;/div&gt;`;</pre><pre>      document.querySelector(&#39;.grid-container&#39;).innerHTML += chatMarkup;</pre><pre>      addEvents(chat.id);</pre><pre>      getMessages(chat);</pre><pre>   }</pre><pre>}</pre><p>The basic flow of this code is as follows: when the getChats() function is called, a fetch request is made to the server which pulls all of the chats between different users. Next, each of those chat objects is iterated over with the renderChat() function, which sorts each chats that includes the current user, either as a sender or a recipient within the chat, before adding them to the page using .innerHTML += chatMarkup.</p><p>Finally, two more functions are called — addEvents(), which creates event listeners for the buttons to send messages in each chat, and getMessages, which sorts the nested messages out of each chat and adds them to each chat window:</p><pre>function addEvents(id){ </pre><pre>   document.querySelector(`.chat-form-chat-${id}`).addEventListener(&quot;submit&quot;, function(e){</pre><pre>      e.preventDefault();</pre><pre>      const messageInput = document.querySelector(`#chat-form-chat-${id}`).value</pre><pre>      postMessage(messageInput, id);</pre><pre>   });</pre><pre>}</pre><p>Is it the most efficient build in the history of chat apps? Probably (almost certainly) not, but for the most part, this works — it sorts through data and makes information like chats and messages visible to the user. However, one bizarre bug that came out of this was that the event listener assigned to the “submit” button (sending a chat) would only work on the final chat window added to the div.</p><p>The issue was my use of <em>innerHTML +=. </em>This specific method wipes out everything inside the div that I am calling it on, then recreates it along with whatever is being added. So if you’re adding chat windows, it’s helpful to have a clearChats() function. In the case of event listeners, this method is especially destructive: every new eventListener added clears out the ones before it.</p><p>One simple solution was to refactor my renderChat() function so that instead of using innerHTML += on the chat markup, I first create a div <em>chatWindow</em> which can then be appended:</p><pre>function renderChat(chat){</pre><pre>   if ((chat.attributes.sender_id.toString() === currentUserId.toString()) || (chat.attributes.recipient_id.toString() === currentUserId.toString())){</pre><pre>   const chatWindow = document.createElement(&quot;div&quot;)</pre><pre>   const chatMarkup =`</pre><pre>   &lt;div class = &quot;chat&quot;, id = &quot;chat-${chat.id}&quot;&gt;</pre><pre>      &lt;h3&gt;Chat between ${chat.attributes.recipient.name} and ${chat.attributes.sender.name}&lt;/h3&gt;</pre><pre>      &lt;div class = &quot;messages&quot;&gt; &lt;/div&gt;</pre><pre>         &lt;form method=&quot;post&quot; class = &quot;chat-form-chat-${chat.id}&quot;&gt;</pre><pre>            &lt;input class=&quot;message-compose-area&quot; id = &quot;chat-form-chat-${chat.id}&quot; type=&quot;text&quot; name=&quot;body&quot;&gt;&lt;/input&gt;</pre><pre>            &lt;input type=&quot;submit&quot; value=&quot;Gab&quot; class=&quot;send-message&quot; id= &quot;gab-button-${chat.id}&quot;&gt;&lt;/input&gt;</pre><pre>         &lt;/form&gt;</pre><pre>      &lt;/div&gt;`;</pre><pre>   chatWindow.innerHTML += chatMarkup;</pre><pre>   document.querySelector(&#39;.grid-container&#39;).append(chatWindow);</pre><pre>   addEvents(chat.id);</pre><pre>   getMessages(chat);</pre><pre>   }</pre><pre>}</pre><p>Just by switching the order of first creating a chatWindow div element, then appending chatMarkup to that before appending to the document, the event listeners were able to be added in each loop of the getChats() function.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b13cba10cdf8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[An Exhaustive, Nested Form with dropdown guide]]></title>
            <link>https://ian-marshall.medium.com/an-exhaustive-nested-form-with-dropdown-guide-bc051ed04eee?source=rss-4220b3b0e6fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/bc051ed04eee</guid>
            <dc:creator><![CDATA[Ian Marshall]]></dc:creator>
            <pubDate>Thu, 18 Mar 2021 21:08:09 GMT</pubDate>
            <atom:updated>2021-03-18T21:08:09.600Z</atom:updated>
            <content:encoded><![CDATA[<p>Creating forms for nested resources with Ruby on Rails can be a huge headache, but after scouring the internet for every example I could find in order to create one myself, I can offer a few insights.</p><p>This post owes a lot to a few (dare I say incomplete?) resources:</p><ul><li><a href="https://levelup.gitconnected.com/rails-nested-forms-in-three-steps-5580f0ad0e">Rails — Nested Forms in Three Steps</a></li><li><a href="https://guides.rubyonrails.org/form_helpers.html">Rails Guides Action View Form Helpers</a></li></ul><p>My app, <a href="https://github.com/busmother/regrettable"><strong>Regrettable</strong></a>, is a celebrity-notes-app-apologies-app, offering a solution for celebrity notes app apologies by allowing users to sign up, apologize for incidents, and forgive others’ apologies with a Forgive button. Here’s a visualization of the basic schema:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/761/1*0zxb94HErhmmD-jdtZB2pg.jpeg" /></figure><p>While nested forms by themselves are complex, I wanted to create a nested form for incidents and apologies with an option either to use a dropdown of existing incidents or to enter a new incident in a text field along with the apology. This way, users would have the option to be able to log a new incident without having to navigate to a separate form <em>or </em>to select an existing incident to apologize for, which would create a richer user experience overall.</p><p>In order to build a form and the associated controller actions to create and properly associate apologies and incidents, you’ll need to leverage methods in your Model, View, and Controller:</p><p>First, make sure that your child class can accept nested attributes for its parent class. In my case, this meant adding the below to my Apology class:</p><pre>#app/models/apology.rb</pre><pre>class Apology &lt; ApplicationRecord<br>   belongs_to :user<br>   belongs_to :incident, inverse_of: :apologies<br>   has_many :forgivenesses<br>   has_many :users, through: :forgivenesses<br>   validates :body, length: {minimum: 50}<br>   validates :incident, presence: :true<br>   validates :user_id, presence: :true<br>   accepts_nested_attributes_for :incident<br>   .<br>   .<br>   .<br>end</pre><p>and my Incident class:</p><pre>#app/models/incident.rb</pre><pre>class Incident &lt; ApplicationRecord<br>   has_many :apologies, inverse_of: :incident<br>   has_many :users, through: :apologies<br>   validates :name, presence: :true<br>   .<br>   .<br>   .<br>end</pre><p>By analogy, if you want to create a new owner for a dog (like <a href="https://levelup.gitconnected.com/rails-nested-forms-in-three-steps-5580f0ad0e">this</a>), create a new artist for an artwork, create a new account for an invoice, etc, you would want to imitate this relationship between a parent (incident) and child (apology) model. Make sure you have the proper has_many / belongs_to declarations alongside inverse_of in addition to accepts_nested_attributes_for in the child model.</p><p>Next, you’ll want to build your form in your views. I created my form in a partial so that I have the flexibility to render it in multiple places in my app, like if a user wanted to edit their apology, or if you wanted to apologize on an incident view page:</p><pre>#app/views/apologies/_nestedform.html.erb</pre><pre>&lt;%= form_for <a href="http://twitter.com/apology">@apology</a> do |f|%&gt;<br>   &lt;div&gt;<br>   &lt;label for=&quot;incident_id&quot;&gt;Select an incident to apologize for:     &lt;/label&gt;<br>   &lt;%= f.collection_select :incident_id, <a href="http://twitter.com/incidents">@incidents</a>, :id, :name, prompt: true%&gt;<br>   &lt;/div&gt;&lt;br&gt;<br>   &lt;div&gt;<br>   &lt;%= f.fields_for :incident, <a href="http://twitter.com/incident">@incident</a> do |i|%&gt;<br>      &lt;%= i.label :name, &quot;Or log a new incident:&quot; %&gt;<br>      &lt;%= i.text_field :name %&gt;<br>   &lt;% end %&gt;<br>   &lt;/div&gt;<br>   &lt;div&gt;<br>   &lt;%= f.label :body, &quot;Apology:&quot;%&gt;<br>   &lt;%= f.text_area :body%&gt;<br>   &lt;/div&gt;&lt;br&gt;<br>&lt;%= f.submit %&gt;</pre><p>You can see the “nested” part of the nested form right away — as soon as I declare that we’re creating a form for an @apology object, we create a dropdown for existing @incidents and a form field for a new incident.</p><p>It’s important to note that for this form to work you have to declare a few different variables in your controller actions. For the form to render, you have to declare the variables in your apologies_controller’s #new action:</p><pre>#app/controllers/apologies_controller.rb</pre><pre>def new<br>   <a href="http://twitter.com/incidents">@incidents</a> = Incident.all #we need this for the dropdown options to appear<br>   <a href="http://twitter.com/incident">@incident</a> = Incident.new #we need for the new incident field<br>   <a href="http://twitter.com/apology">@apology</a> = Apology.new #we need this for the apology field<br>end</pre><p>Interestingly enough, without declaring @incident, the form would still render, but without a text field for the new incident name.</p><p>You may see other versions of this #new action to create the same result — another way of writing this could be:</p><pre>def new<br>   <a href="http://twitter.com/apology">@apology</a> = Apology.new<br>   <a href="http://twitter.com/apology">@apology</a>.build_incident<br>end</pre><p>One issue I ran into with this method was that it implicitly links the new incident with the new apology — we’ll always be creating a new apology either way, but I wanted to keep the flexibility of associating that apology with an existing incident rather than create a new incident every time.</p><p>Now that we have the form (albeit with little to no formatting), we can turn to the #create action in the apologies controller:</p><pre>#app/controllers/apologies_controller.rb</pre><pre>def create #new create<br>   if params[:apology][:incident_id].to_i &gt; 0 #if you use the dropdown there will be an incident_id &gt;0; if not, it will be &quot;&quot;, which is 0<br>      <a href="http://twitter.com/incident">@incident</a> = Incident.find(params[:apology][:incident_id]) # so we find the incident<br>   else<br>      <a href="http://twitter.com/incident">@incident</a> = Incident.find_or_create_by(name: params[:apology][:incident_attributes][:name])#this works if you use the form<br>   end<br>   <a href="http://twitter.com/apology">@apology</a> = Apology.new(user_id: current_user.id, incident_id: <a href="http://twitter.com/incident">@incident</a>.id, body: params[:apology][:body])<br>   if <a href="http://twitter.com/apology">@apology</a>.valid?<br>      <a href="http://twitter.com/apology">@apology</a>.save<br>      redirect_to incident_path(<a href="http://twitter.com/incident">@incident</a>)<br>   else<br>      flash.now[:messages] = <a href="http://twitter.com/apology">@apology</a>.errors.full_messages<br>      <a href="http://twitter.com/incidents">@incidents</a> = Incident.all<br>      render :new<br>   end<br>end</pre><p>There’s a lot happening here (and I will be the first to admit that there can be more than one way to organize this information!) but the broad strokes of this method hinge on two if/else statements.</p><p>First: #create checks the nested params for an incident_id — this would only be present if the user selects an existing incident from the dropdown menu. Since an incident_id will always be a number greater than 0, the first conditional evaluates as true if the user has chosen an existing incident. (Why do only existing incidents have ids, you ask? Well, remember that at this point @incident is simply a blank incident class instance — it hasn’t been persisted to our database, so it hasn’t been assigned an id). If our user did not select an existing incident, then the :incident_id parameters would simply be “”, a blank string, which when converted to an integer would evaluate as 0.</p><p>Once this first conditional evaluates, the method assigns @incident to either an existing incident (a choice from the dropdown) or creates a new one with the :name parameter passed in through the form.</p><p>Next, a new apology is created with a user_id of the current_user’s id, the body text passed through the form, and the incident_id from our freshly minted @incident variable. At this point, it doesn’t matter whether our user created a new incident or selected an existing one — @incident is the incident. (It’s also worth noting that current_user is a built-in method if you’re using the <a href="https://github.com/heartcombo/devise">Devise</a> gem, but you could also define a method that captures that information.)</p><p>The second conditional checks whether the new apology is valid (does it satisfy the minimum length? Does it have a user_id?). If yes, the @apology variable is saved and persists in our database. The user is redirected to the @incident view where they can see their apology in a string of other apologies for the same incident (or if they created a new incident, it will be alone). If the apology is not valid (maybe it was too short), an error will appear that will alert the user of the issue when the page reloads. This method also has the benefit of reloading the information the user has written so far — if it were to redirect_to apologies#new, it would create a blank form, which would be frustrating since you’d have to start your apology from scratch.</p><p>Without the first conditional, I experienced issues where apologies were returned as invalid because they didn’t have incidents associated with them. Without the second, the integrity of the data you’re trying to collect with your hard-fought, nested form is in jeopardy.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bc051ed04eee" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Sessions, redirects, and when to set instance variables]]></title>
            <link>https://ian-marshall.medium.com/sessions-redirects-and-when-to-set-instance-variables-86d1a691b505?source=rss-4220b3b0e6fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/86d1a691b505</guid>
            <dc:creator><![CDATA[Ian Marshall]]></dc:creator>
            <pubDate>Thu, 18 Feb 2021 20:57:01 GMT</pubDate>
            <atom:updated>2021-02-19T16:49:50.955Z</atom:updated>
            <content:encoded><![CDATA[<p>If you click on <a href="http://www.medium.com/">this link</a>, your browser should take you to the Medium home page. You’re not asked to log in again, and you should still see your icon in the top right corner that shows the site knows who you are. Staying logged in from one page to another is an underrated fact of our experience using the web that relies on a few simple operations working together.</p><p>When a user logs into a website, the client (your browser) makes a request to the server, which prompts the server to initiate a <em>session</em>. At the end of the day, a session is simply a hash with key-value pairs, including the session ID, which matches the user’s ID and helps identify the user on other pages of the website. Other key-value pairs in the session hash include an expiration date when the session will end, metadata (like whether this particular user is an admin or not), and even login attempts. The session hash is stored in the database until it is cleared, either once the session expires or when the user logs out.</p><p>Sessions are a piece of data that a server employs to keep track of a user as they navigate around a website.</p><p>All of this keeps the “state” of the user on the server, which is hugely useful for our experience of the web because the language of requests between the client/browser and the server, HTTP, is stateless. HTTP (Hypertext Transfer Protocol) can be summarized as a system of rules that directs how data is exchanged between a browser/client and a server. Each request is independent from any other requests that have already been made or may be made in the future — simply, it does not inherently track what a user has already done without this session hash. The session acts as a kind of name tag (:loginAttempts =&gt; 4) and the site can recognize this behavior (“I am the same user that had to attempt my login four times”).</p><p>Using sessions to recognize users is essential to the way we use the web. When writing the views for a particular website, controller method variables are often set as instance variables like @user or @users. The application’s controller invokes the methods that define these variables, (in the case of @user, typically relying on the information in the session hash), before rendering a view or redirecting to another view.</p><p>There is a key difference between rendering a view and redirecting to a route as it relates to how the @user variable is defined: when a user clicks on a button or types in the URL line, a request is made between the client/browser and the server; when redirecting, a <em>new</em> request is made and that request is routed to a <em>separate controller method</em>. Each request corresponds to a new instance of the controller class, and the brand new controller object must have the same instance variables established for the variables in the view to render correctly. Since we don’t have access to the controller variables after redirecting, errors like “NoMethodError: undefined method ‘[]’ for nil:NilClass” are common in situations like these because the variable @user is not defined in the controller path that led to that new view. Rendering a page like ‘edit’ can work as intended because @user is defined in the controller, but redirecting to the same page might not if @user is not defined in the controller.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=86d1a691b505" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Creating next/back buttons in HTML]]></title>
            <link>https://ian-marshall.medium.com/creating-next-back-buttons-in-html-199ffa58b0af?source=rss-4220b3b0e6fb------2</link>
            <guid isPermaLink="false">https://medium.com/p/199ffa58b0af</guid>
            <dc:creator><![CDATA[Ian Marshall]]></dc:creator>
            <pubDate>Sat, 13 Feb 2021 18:32:21 GMT</pubDate>
            <atom:updated>2021-02-13T18:32:21.797Z</atom:updated>
            <content:encoded><![CDATA[<p>One of the most vexing and difficult parts of creating <a href="https://github.com/busmother/deckar">a Sinatra flashcard application</a> is the core functionality of the flash cards themselves: navigating back and forth within the deck. If I were building this application using Javascript, these navigations could be more streamlined, but since this application relies solely on Ruby, ActiveRecord, and HTML I had to find a RESTful way to execute the three actions of next and back.</p><p>My application has a user class, which has many decks and many cards through decks; decks belong to one user and have many cards; finally, cards belong to a deck and belong to a user through the deck. Here’s the same information summarized in the schema:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/830/0*pDUQwjxt8CwEtglf" /></figure><p>To understand how we would navigate from one card to the next, we can start by considering the URL that will take us to a specific card in a deck.</p><p>The card view URL consists of four components:</p><pre>‘/decks/:slug/cards/:id’</pre><p>First, <strong>deck</strong> tells us that we’re going to be looking at a deck, then the unique <strong>slug</strong> tells us which deck we’re looking at in particular; similarly, <strong>cards</strong> tells us we’re going to be looking at a card, then the unique <strong>id</strong> tells us which card we’re looking at in particular. The most basic way to navigate from one to the next would be by simply adding 1 (+1) to the id so you can go from card number 5 to card number 6.</p><p>This relates to how the cards are each made. If I were going to create a new deck from scratch, I would create them all at once — here’s a simple version of the cards controller’s <em>create</em> action:</p><pre>post &#39;/decks/:slug/cards&#39; do #create action, creates cards</pre><pre>   @deck = Deck.find_by_slug(params[:slug])</pre><pre>   params[:front].each_with_index do |front, i|</pre><pre>      front = params[:front][i]</pre><pre>      back = params[:back][i]</pre><pre>      card = Card.create(front: front, back: back, deck_id: @deck.id)</pre><pre>   end</pre><pre>   erb :&#39;/decks/deck_show&#39;</pre><pre>end</pre><p>Let’s break this down: the empty deck is identified by the slug in the URL; next, the front and back of each card, which are accepted as two separate arrays, are matched one by one to create new cards that share the same deck id. When creating a new deck of cards, you would expect each card’s individual ID would be sequential since they are being made at the same time — five cards in a deck would have ids like 1, 2 ,3, 4, and 5 or 43, 44, 45, 46 and 47. This means that creating a very simple next / back navigation in HTML would look like this:</p><pre>&lt;form action=’/decks/&lt;%=@deck.slug%&gt;/cards/&lt;%=@card.id+1%&gt;’ method=”get”&gt;</pre><pre>&lt;button type=”submit”&gt;Next&lt;/button&gt;</pre><pre>&lt;/form&gt;</pre><p>By simply adding 1 (or subtracting 1 for ‘back’), a user can navigate through a deck by leveraging the unique, sequential ids that are given to the cards when they’re created. However, <em>this is not a foolproof method if the decks of cards are ever edited</em>. For example, what if we remove one card? The sequence of card ids might change from 4, 5, 6 to 4, then 6, and since there’s no card with a corresponding id of 5, the form action would render a page with no corresponding card object. Another issue would come up when adding cards later on: if the original deck had card ids of 4, 5, 6 before three new cards were added, it’s very likely that those cards wouldn’t be 7, 8, and 9, but rather 33, 34, and 35. Remember, since each card’s id is unique across all decks in the application, there are other users adding cards to their own decks. Taking the card id and adding 1 is not a robust enough method to navigate from card 6 to card 34.</p><p>Since cards <em>belong to</em> a deck, ActiveRecord already adds card instances to an array in each deck when they are created, which is a much better place to start when thinking about next and back buttons. Here’s an example of a deck viewed in pry:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CLS0SAG4A-Q_YRy1" /></figure><p>You can see how each card has the same deck_id, but the individual card ids in blue go from 7–12 before jumping to 33.</p><p>How can we create a meaningful link instead of simply adding or subtracting 1 from the id? First, we first want to create an array of all the card ids in a deck in our cards controller. Here’s a show action route from the cards controller:</p><pre>get ‘/decks/:slug/cards/:id’ do #show action, displays one card based on id in URL</pre><pre>   @deck = Deck.find_by_slug(params[:slug])</pre><pre>   @cards = @deck.cards</pre><pre>   @ids = []</pre><pre>   @cards.each do |card|</pre><pre>      @ids &lt;&lt; card.id</pre><pre>   end</pre><pre>   @card = @cards.find_by_id(params[:id])</pre><pre>   erb :’cards/cards_show_front’</pre><pre>end</pre><p>The next/back navigation tool begins on the 5th line. First, an empty array named @ids is defined, which is filled with the individual card id of each card in the deck. Then, in the corresponding view, we can render the URL of what the next card will be by finding what the following card id will be after the card we’re looking at:</p><pre>&lt;form action= ’/decks/&lt;%=@deck.slug%&gt;/cards/&lt;%=@deck.cards[(@deck.cards.find_index(@card)+1)].id%&gt;/ method=”get”&gt;</pre><pre>&lt;button type=”submit”&gt;Next&lt;/button&gt;</pre><pre>&lt;/form&gt;</pre><p>The difference between this button and the earlier version begins after /cards/. We can take a closer look step by step. Broadly, I’m using the array @deck.cards and asking for the id for a specific card — you can think of it like this:</p><pre>@deck.cards[“some index”].id #the id of the next card in the deck.</pre><p>Within the brackets, I first have to identify the index of the card we’re already on by calling the deck’s array of cards, and then finding by the index of the card we’re already looking at:</p><pre>@deck.cards.find_index(@card) #the index of the card we’re already looking at.</pre><p>Since the array @ids only holds the unique card ids, we can easily find the next number by adding 1 not to the card’s id, but it’s place in the index. Putting it all together, we get:</p><pre>@deck.cards[(@deck.cards.find_index(@card)+1)].id</pre><p>As an added layer of functionality, I can make sure that the button for next only shows up if there <em>is</em> a next card, using the @ids array again. In the card show view, I wrap the the button html in some Ruby logic:</p><pre>&lt;%if @card.id != @ids.max%&gt;</pre><pre>   &lt;form action= ’/decks/&lt;%=@deck.slug%&gt;/cards/&lt;%=@deck.cards[(@deck.cards.find_index(@card)+1)].id%&gt; method=”get”&gt;</pre><pre>   &lt;button type=”submit”&gt;Next&lt;/button&gt;</pre><pre>   &lt;/form&gt;</pre><pre>&lt;%end%&gt;</pre><p>In the first line, Ruby confirms that the id of the card we’re already looking at is not the largest card id in the deck — if it is, then the statement returns false, and the button does not display. Similarly, for the back button if the id is not the minimum, then the back button displays:</p><pre>&lt;%if @card.id != @ids.min%&gt;</pre><pre>   &lt;form action= ’/decks/&lt;%=@deck.slug%&gt;/cards/&lt;%=@deck.cards[(@deck.cards.find_index(@card)-1)].id%&gt; method=”get”&gt;</pre><pre>   &lt;button type=”submit”&gt;Back&lt;/button&gt;</pre><pre>   &lt;/form&gt;</pre><pre>&lt;%end%&gt;</pre><p>More complicated methods must be created if you want to sort or reorder your cards beyond their given id numbers, but this method ensures that each card can be viewed one at a time and that the buttons will only show up when they have a function.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=199ffa58b0af" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>