<?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 Edward Norton on Medium]]></title>
        <description><![CDATA[Stories by Edward Norton on Medium]]></description>
        <link>https://medium.com/@eanorton?source=rss-4cbfd0c15542------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*1jYvvsJBN76Zr5eukxrLiA.jpeg</url>
            <title>Stories by Edward Norton on Medium</title>
            <link>https://medium.com/@eanorton?source=rss-4cbfd0c15542------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 14:41:19 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@eanorton/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[Error Handling in JavaScript]]></title>
            <link>https://medium.com/@eanorton/error-handling-in-javascript-aea467b0a0aa?source=rss-4cbfd0c15542------2</link>
            <guid isPermaLink="false">https://medium.com/p/aea467b0a0aa</guid>
            <dc:creator><![CDATA[Edward Norton]]></dc:creator>
            <pubDate>Fri, 28 Sep 2018 21:35:39 GMT</pubDate>
            <atom:updated>2018-09-28T21:35:39.311Z</atom:updated>
            <content:encoded><![CDATA[<h4>A brief overview of try…catch</h4><p>What distinguishes good code from bad, is code that preemptively deals with errors in a program, and prevents it from crashing. Code should handle errors by anticipating edge cases, informing the user about it, or logging the error somewhere. Error handling — and the primary mechanism for error handling — in JavaScript is the try…catch construct.</p><p>So let’s take a brief look at how to use try…catch, and how to throw our own custom errors.</p><h3>try…catch</h3><p>To begin, let’s look at the basic syntax for try…catch:</p><pre>try {<br>  // code...<br>} catch (err) {<br>  // error handling<br>}</pre><p>Notice how the catch block gets access to an error object, (err). When an error occurs, JavaScript generates an object containing the details about it. The object is then passed as an argument to catch.</p><p>For all built-in errors, the error object inside the catch block has two main properties: name and message. name is the name of the error (crazy, I know) — for an undefined variable, that will be “ReferenceError”. message if you haven’t figured out by now, is a message with error details. In most environments the error object will also have a stack property with the stack trace leading to the error.</p><p>If you log the error object to the console, it’s name and message properties will be concatenated together.</p><p>Here’s an example where we misspell a variable name:</p><pre>let exampleVariable = 50;</pre><pre>try {<br>  console.log(exampleVarible + 50);<br>} catch (err) {<br>  console.log(&#39;OH NO -&#39;, err);<br>}</pre><p>In this case, the catch block will be executed and the following message is printed to the console:</p><pre>OH NO - ReferenceError: exampleVarible is not defined</pre><p>try…catch only handles errors encountered at runtime, and invalid JavaScript will error-out at parse-time so your program won’t run at all.</p><h3>Custom Errors</h3><p>Instead of catching pure JavaScript errors all the time, we will likely want to catch other conditions that should also be considered errors. For this, we can make use of the throw statement to throw our own errors in a try block so that the error can be caught and dealt with.</p><p>An example might look something like this:</p><pre>let exampleVariable = prompt(&#39;Please enter a number:&#39;)</pre><pre>try {<br>  if (isNaN(+exampleVariable)) {<br>    throw new Error(&#39;woah woah woah, that is not a number&#39;);<br>  } console.log(exampleVariable, &#39;is my favorite number!&#39;);<br>} catch (err) {<br>  console.log(err);<br>}</pre><p>With the above example, if we don’t enter a value that is evaluated as a string, we throw a custom error that’s then caught by our catch block.</p><p>We can also make use of the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Error">Error constructor</a> in order to create a TypeError object with a custom message passed in as the first argument. TypeError creates an instance representing an error that occurs when a variable or parameter is not of a valid type.</p><pre>try {<br>  if (isNaN(+exampleVariable)) {<br>    throw new TypeError(&#39;Not a number&#39;);<br>  } console.log(exampleVariable, &#39;is my favorite number!&#39;);<br>} catch (err) {<br>  console.log(err);<br>}</pre><h3>try…catch…finally</h3><p>The try..catch construct has one more clause: finally. If finally exists, it runs in all cases: if after try there were no errors, or after catch and there were errors.</p><p>The extended syntax looks like this:</p><pre>try {<br>  ... try to execute ...<br>} catch (err) {<br>  ... handle errors ...<br>} finally {<br>  ... execute always ...<br>}</pre><p>Try running this code that <a href="http://javascript.info/">javascript info</a> put together to see for yourself!:</p><pre>try {<br>  alert( &#39;try&#39; );<br>  if (confirm(&#39;Make an error?&#39;)) BAD_CODE();<br>} catch (err) {<br>  alert( &#39;catch&#39; );<br>} finally {<br>  alert( &#39;finally&#39; );<br>}</pre><p>As you can see if you tried both options, the code has two different executions, but it will always hit finally:</p><ol><li>“Yes” hits try -&gt; catch -&gt; finally.</li><li>“Cancel” hitstry -&gt; finally.</li></ol><p>The finally clause is often used when we start doing something before try..catch and want to finalize it <em>in any case of outcome</em>.</p><h3>The takeaway</h3><p>The try..catch construct allows us to handle runtime errors. It is what allows us to try running code and catch errors that may occur. It’s an extremely useful practice to dig into!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=aea467b0a0aa" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Component Elements]]></title>
            <link>https://medium.com/@eanorton/react-component-elements-9dffad06b198?source=rss-4cbfd0c15542------2</link>
            <guid isPermaLink="false">https://medium.com/p/9dffad06b198</guid>
            <dc:creator><![CDATA[Edward Norton]]></dc:creator>
            <pubDate>Fri, 21 Sep 2018 22:06:03 GMT</pubDate>
            <atom:updated>2018-09-21T22:06:03.635Z</atom:updated>
            <content:encoded><![CDATA[<h4>And how to access them</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*fA_cSQkUrV5Udj2075VQZg.png" /></figure><p>JSX is an amazing syntax extension for JavaScript — an extension which React utilizes well. I enjoy writing JSX so much, it’s partly what drew me to React.</p><p>An unfortunate drawback of JSX, however, is that it can complicate accessing component elements. That being said, accessing a component’s own elements in React is relatively easy. So let’s look at how a component method can access its own DOM node:</p><p>As the <a href="https://reactjs.org/docs/refs-and-the-dom.html">React documentation</a> explains, the method for getting DOM nodes is by using refs.</p><blockquote>Refs are created using React.createRef() and attached to React elements via the refattribute. Refs are commonly assigned to an instance property when a component is constructed so they can be referenced throughout the component.</blockquote><pre>class MyComponent extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    this.myRef = React.createRef();<br>  }<br>  render() {<br>    return &lt;div ref={this.myRef} /&gt;;<br>  }<br>}</pre><p>Once a ref is passed to an element using render, a reference to the node becomes accessible with the current attribute of the ref.</p><pre>const exampleNode = this.myRef.current;</pre><p>The value of the ref will be different depending on the type of the node:</p><blockquote>When the ref attribute is used on an HTML element, the ref created in the constructor with React.createRef() receives the underlying DOM element as its current property.</blockquote><blockquote>When the ref attribute is used on a custom class component, the ref object receives the mounted instance of the component as its current.</blockquote><blockquote><strong>You may not use the </strong><strong>ref attribute on functional components</strong> because they don’t have instances.</blockquote><p>Adding a ref attribute to an element you want to have a handle on is the React-based approach you can take. I encourage you to take a deeper dive into the documentation and explore refs more!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9dffad06b198" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cookie Monster]]></title>
            <link>https://medium.com/@eanorton/cookie-monster-e3d7b1dffcf7?source=rss-4cbfd0c15542------2</link>
            <guid isPermaLink="false">https://medium.com/p/e3d7b1dffcf7</guid>
            <dc:creator><![CDATA[Edward Norton]]></dc:creator>
            <pubDate>Fri, 14 Sep 2018 22:31:37 GMT</pubDate>
            <atom:updated>2018-09-14T22:31:37.265Z</atom:updated>
            <content:encoded><![CDATA[<h4>The difference between first-party and third-party cookies.</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FxT0xeMA62E1XIlup68%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fsesamestreet-xT0xeMA62E1XIlup68&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FxT0xeMA62E1XIlup68%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/ebaf59ea7eebcf160ec799eeb3acd416/href">https://medium.com/media/ebaf59ea7eebcf160ec799eeb3acd416/href</a></iframe><h4>What is a cookie?</h4><p>A cookie is a delicious baked good that usually contains flour, sugar, fat, chocolate chips, and… okay, okay, this joke has been done before.</p><p>A <em>web</em> cookie, simply put, is data sent from a website and stored on a user’s computer via their web browser. Cookies were designed for websites to be able to track a user’s ID session, preferences, and navigation —ultimately a mechanism by which a website can remember browsing activity and stateful information.</p><p>Depending on the cookie, it can be stored on a user’s computer for minutes, days, weeks, or months. A session cookie exists in temporary memory only while the user navigates a specific website, while a typical analytics cookie might be stored for 30–60 days.</p><p>There are two different types of cookies, dependent on what type of website sets them: first-party and third-party. The difference between them ultimately boils down to what domain created the cookies in the first place.</p><h4>First-Party Cookies</h4><p>A first-party cookie refers to a cookie <strong>created by the domain that a web user is visiting</strong>. For example, when a user visits Twitter.com on their browser, that browser sends a web request to interact with the site. The site will respond and the web browser will then save this data file to the user’s computer under the Twitter.com domain.</p><h4>Pros</h4><ul><li>First-party cookies remember a user’s personal information, so whenever the user revisits the site, they will not have to re-enter information again.</li><li>You are able to track what people do on your site. You can see how long they stayed, what pages they viewed, how many pages they were on, and track if they purchased anything.</li><li>Leads to generating personalized content that will be geared towards user preferences.</li><li>Analytics, such as tracking what pages perform well and which pages need improvement.</li></ul><h4>Cons</h4><ul><li>Limited to domain. Once a user leaves your site, you are unable to see what they do.</li><li>You are not able to track individual users on the same computer, unless they specifically enter separate login credentials.</li></ul><h4>Third-Party Cookies</h4><p><strong>Third-party cookies are set by a third-party domain</strong>. This sort of cookie appears when web pages feature content from other websites (such as text ads, banner ads, etc.). This enables tracking a user’s browsing history and is used by advertisers to serve relevant ads to specific users.</p><h4>Pros</h4><ul><li>Great for marketing research and identifying successful or ineffective marketing campaigns.</li><li>Able to track a user across multiple domains.</li><li>Therefore, it is easier to identify what a user did after they visited your site.</li></ul><h4>Cons</h4><ul><li>Third-party cookies often get blocked.</li><li>Information can be stolen if the session in unencrypted.</li><li>There could be other tracking options that a third-party company add to the cookie that you are not aware of.</li></ul><h4>The takeaway</h4><p>A cookie is the data sent from a website and stored on a user’s computer via their web browser. Whether you allow first-party and/or third-party cookies is up to you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e3d7b1dffcf7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[THE CUBE]]></title>
            <link>https://medium.com/@eanorton/the-cube-d49bddc246d4?source=rss-4cbfd0c15542------2</link>
            <guid isPermaLink="false">https://medium.com/p/d49bddc246d4</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[threejs]]></category>
            <dc:creator><![CDATA[Edward Norton]]></dc:creator>
            <pubDate>Tue, 17 Jul 2018 02:55:46 GMT</pubDate>
            <atom:updated>2018-07-17T13:17:27.755Z</atom:updated>
            <content:encoded><![CDATA[<h4><strong>Exploring Three.js and a rendering a basic 3D cube</strong></h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Fedwardnorton%2Fembed%2Fpreview%2FLBNdNp%3Fheight%3D600%26slug-hash%3DLBNdNp%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io%26embed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Fedwardnorton%2Fpen%2FLBNdNp&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fm.cdpn.io%2Fscreenshot-coming-soon-small.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bb31cc576c0252eeaedbf80943b0443/href">https://medium.com/media/3bb31cc576c0252eeaedbf80943b0443/href</a></iframe><h4><strong>What is Three.js?</strong></h4><p><a href="https://threejs.org/">Three.js</a> is a cross-browser JavaScript library/API used to create and render 3D objects on a browser. Three.js scripts are used along with the HTML5 &lt;canvas&gt; element, SVG (Scalable Vector Graphics — which defines vector-based graphics in XML format) or WebGL (another JavaScript API for rendering interactive 2D and 3D graphics inside an HTML &lt;canvas&gt; element).</p><p>The main thing to keep in mind when starting to work with three.js, is that in order to actually be able to display anything, you must first establish a Scene, Camera, and Renderer.</p><h4>Renderer, Camera, Scene</h4><p>The Renderer is the place where we are going to put the result of our Scene, and the Camera is the way in which we view the Scene. The Scene is ultimately where you place your objects, lights, and cameras. We can have multiple Scenes, and each one can have different objects, but they will be viewed through whichever Camera we establish. One of the most common Cameras used is the Perspective Camera, which, according to the documentation, is designed to mimic the way the human eye sees.</p><p>The next thing we need to understand about three.js is the Geometry, Material, and Mesh.</p><h4>Geometry, Material, Mesh</h4><p>Geometry defines the shape of the objects we draw in Three.js and is made up of a collection of vertices. A Material is the collection of properties and behaviors of an object, along with the light sources for the Scene. As for the Mesh, it is the composition of a Geometry along with a Material.</p><p>Now that we are at least somewhat familiar with the basics of Three.js, let’s dig into the documentation and we should be able to build the cube above!</p><p>Looking at the first step in the <a href="https://threejs.org/docs/index.html#manual/introduction/Creating-a-scene">documentation</a>, we’ll see that we need to establish where we want to display our cube. Either create an index.html file, or if you want to play around with it on a <a href="https://codepen.io/edwardnorton/pen/LBNdNp">codepen</a>, include the minified cdn in the script.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6124214aa5c23250b13b42ff6c3585b9/href">https://medium.com/media/6124214aa5c23250b13b42ff6c3585b9/href</a></iframe><p>Now we want to go into our .js file and create an empty scene:</p><p>const scene = new THREE.Scene();</p><p>Next, create the camera and set the position. We can adjust the distance of our object from the camera by modifying camera.position.z — the smaller the number, the closer it will be, and larger will be further away. Mess around with the numbers you pass in to get a better feel for how the position is set.</p><pre>const camera = new THREE.PerspectiveCamera( 75, window.innerWidth/window.innerHeight, 0.1, 1000 );<br>camera.position.z = 3.5;</pre><p>Now we will want to create a renderer, and be sure to switch the <a href="https://threejs.org/docs/#api/renderers/WebGLRenderer.antialias">antialias</a> from its default ‘false’ to ‘true’ in order to clean up those jagged edges!</p><p>const renderer = new THREE.WebGLRenderer({antialias:true});</p><p>We’ll also now configure the renderer background color and set the size:</p><pre>renderer.setClearColor(“#000000”);<br>renderer.setSize(window.innerWidth, window.innerHeight);</pre><p>After we’ve set the color and size, the next step is to append the Renderer to the DOM:</p><p>document.body.appendChild(renderer.domElement);</p><p>Now that we have our Scene established with the Camera and Renderer, we will be able to create the cube and set the material. You can look into the documentation for finding more information about the different mesh materials, such as depth, phong, etc. But for now, we’ll stick to the basic mesh and set the size of it’s geometry:</p><pre>const geometry = new THREE.BoxGeometry(2, 2, 2);<br>const material = new THREE.MeshBasicMaterial({ color: “#CCCCCC” });<br>const cube = new THREE.Mesh(geometry, material);</pre><p>Now we add the cube to the Scene:</p><p>scene.add(cube);</p><p>Once the cube has been set, we’ll want to render the cube so that it also rotates as a loop and on which axis:</p><pre>const render = () =&gt; {<br> requestAnimationFrame(render);</pre><pre> cube.rotation.x += 0.00;<br> cube.rotation.y += 0.02;</pre><pre>// Be sure to render the scene!<br> renderer.render(scene, camera);<br>};</pre><p>Now we can call the render:</p><p>render();</p><p>And there we have it! We have now just created a 3D cube in our browser!</p><h3>Takeaway</h3><p>I hope you’ve found this brief introduction and walk through of the Three.js documentation helpful — or at the very least interesting. Creating 3D objects in the browser can be a lot of fun, and hopefully this gives you an idea of what you can do using the Three.js library.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d49bddc246d4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Console.log(“tips”)]]></title>
            <link>https://medium.com/@eanorton/console-log-tips-bfb461a83763?source=rss-4cbfd0c15542------2</link>
            <guid isPermaLink="false">https://medium.com/p/bfb461a83763</guid>
            <category><![CDATA[flatiron-school]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[console]]></category>
            <dc:creator><![CDATA[Edward Norton]]></dc:creator>
            <pubDate>Thu, 14 Jun 2018 01:54:55 GMT</pubDate>
            <atom:updated>2018-06-14T12:45:03.194Z</atom:updated>
            <content:encoded><![CDATA[<h4>Taking advantage of more tools in the console</h4><p>The console is an invaluable resource for developers. While there are things like the debugger that are readily available to us, there are a myriad of other tools that can be utilized for debugging, styling, and exploring code in the console further.</p><h3>console.table()</h3><p>If you’re ever working with a complex set of objects, you could either console.log them the old fashioned way and scroll through the returns in your console. Or, if you’re in the mood for something else, you could take a seat at the console.table(). It can make it easier to reference your objects and sort by how you want your objects to appear. And let’s be honest, it’s pretty neat.</p><pre>let characters = [<br>    { name: &quot;Gandalf&quot;, movie: &quot;Lord of the Rings&quot;, age: 2019 },<br>    { name: &quot;Ellen Ripley&quot;, movie: &quot;Alien&quot;, age: 30 },<br>    { name: &quot;Dr. Henry Walton Jones Jr.&quot;, movie: &quot;Indiana Jones&quot;, age: 32 }<br>];</pre><pre>console.table(characters);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*x7xsnWZCJ3J1jnffU-Xofg.png" /></figure><h3>DOM Element Marking</h3><p>You can mark a DOM element in your Elements panel and use it in your console. The Google Chrome Inspector stores the five most recent elements that have been marked in its memory, which you can then quickly access and store as a variable in your console by using $0, $1, $2, $3, $4.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*G8QrS1lx2tEtgLpfvf0oYQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*IpEX-3Eg8Gj2LtEWegiN_A.png" /></figure><h3>Edit Directly in the DOM</h3><p>You can edit almost anything straight from your browser — either add text or remove text directly in the DOM.</p><p>To enable this functionality, go into your console and enter:</p><p>document.body.contentEditable=true</p><p>Now you can manipulate directly in the browser window.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qNmj01wEQyycl3qgdv6KUQ.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*htyxdjoDvC7X_7owQyWu2w.png" /></figure><h3>$_</h3><p>using $_ in your console will retrieve the result of the last expression executed in your console’s command line. If you’re needing to do some quick math, it will retrieve your last result, or if a function returns an array, you can quickly set that array to a variable by setting a declaration equal to $_.</p><h3>Eyedropper</h3><p>In the Elements panel in your console, you can alter or grab the color codes using the built in eyedropper tool through the Styles tab. To do this, simply find whichever element contains a color box, select it, and it will open your color manipulation options.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Yp_GhkbJqwEHsWoL76YQtw.png" /></figure><h3>Clearing the Console</h3><p>Last but not least, it’s time to clean up your space. There are two main ways to clear your console — the first is by entering console.clear() and the other is simply cmd+k. Easy!</p><p>Above are just a few examples of the many tools we have at our disposal using Chrome’s console. I highly recommend looking into more, many of which you can find more information about on <a href="https://developer.mozilla.org/en-US/docs/Tools/Web_Console">MDN</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bfb461a83763" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Death to Smoothy?]]></title>
            <link>https://medium.com/@eanorton/death-to-smoothy-b36985a60aeb?source=rss-4cbfd0c15542------2</link>
            <guid isPermaLink="false">https://medium.com/p/b36985a60aeb</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Edward Norton]]></dc:creator>
            <pubDate>Wed, 23 May 2018 11:13:27 GMT</pubDate>
            <atom:updated>2018-05-23T13:13:52.445Z</atom:updated>
            <content:encoded><![CDATA[<h4>Rails and Inflections</h4><p>Hot take: English is crazy (but it’s great and it’s also pretty important when it comes to writing our code). When setting up a new app in Rails, there are certain words that it doesn’t know how to properly inflect, as many of us learned going through the Smoothie discussion question.</p><pre>&quot;smoothies&quot;.singularize</pre><pre>=&gt; &quot;smoothy&quot;</pre><p>SMOOTHY. I can’t even deal.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FCuGrzWCjz0rSM%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FCuGrzWCjz0rSM%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FCuGrzWCjz0rSM%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="472" frameborder="0" scrolling="no"><a href="https://medium.com/media/22e82ed3585f5c63e7b8a095720e01e7/href">https://medium.com/media/22e82ed3585f5c63e7b8a095720e01e7/href</a></iframe><p>In order to begin, we need to cover convention in Rails. We’ve all heard “convention over configuration” by now, but the key to understanding the paradigm is stated in the <a href="https://rubyonrails.org/doctrine/#convention-over-configuration">Rails doctrine</a> as follows:</p><blockquote>“by giving up vain individuality, you can leapfrog the toils of mundane decisions, and make faster progress in areas that really matter.”</blockquote><blockquote>…</blockquote><blockquote>“Not only does the transfer of configuration to convention free us from deliberation, it also provides a lush field to grow deeper abstractions. If we can depend on a Person class mapping to people table, we can use that same inflection to map an association declared as has_many :people to look for a Person class. The power of good conventions is that they pay dividends across a wide spectrum of use.”</blockquote><p>When using Rails, a lot of its functionality seems like magic. Of course, we know it isn’t magic, it’s just really wonderful code that makes our lives easier when we follow the conventions laid out for us. However, as much as we can rely on the established Rails code that we have at our disposal, there are times when we need to be free to express our “vain individuality” and make some “mundane decisions” for ourselves, since it can’t do everything — especially when it comes to naming (on account of English being a totally wild language with endless irregularities).</p><p>Thankfully, there’s a tool to help with this problem: the Inflector.</p><blockquote>The <a href="http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html">Inflector</a> transforms words from singular to plural, class names to table names, modularized class names to ones without, and class names to foreign keys. The default inflections for pluralization, singularization, and uncountable words are kept in inflections.rb.</blockquote><blockquote>The Rails core team has stated patches for the inflections library will not be accepted in order to avoid breaking legacy applications which may be relying on errant inflections. If you discover an incorrect inflection and require it for your application or wish to define rules for languages other than English, please correct or add them yourself (explained below).</blockquote><p>As stated in the documentation, these rules don’t change in order for Rails to remain backwards-compatible for older applications.</p><p>If we start digging into the Rails Inflector, we find that it’s a part of the <a href="https://github.com/rails/rails/tree/efff6c1fd4b9e2e4c9f705a45879373cb34a5b0e/activesupport/lib/active_support/inflector">ActiveSupport</a> module. ActiveSupport is an enormous component within Rails, and is responsible for language extensions and utilities. A gross oversimplification of ActiveSupport is that it provides basic methods that allow us to transform simple strings.</p><p>But what if those methods don’t apply to our app and we run into an edge case that Rails can’t deal with on its own? If we want to create our own custom language or fix existing errors regarding our inflections, we have to specify what irregularities we wish to address for our application. So before we start addressing exceptions, it’s helpful to look at a few of the existing inflector methods that are already available to us within ActiveSupport:</p><h4>Singularize</h4><p>The singularize method returns the singular form of a word in a string:</p><p>&quot;people&quot;<strong>.</strong>singularize =&gt; &quot;person&quot;</p><h4>Pluralize</h4><p>The pluralize method — you guessed it — will give you the plural form of a word as a string:</p><p>&quot;fly&quot;<strong>.</strong>pluralize =&gt; &quot;flies&quot;</p><h4>Titleize</h4><p>The titleize method capitalizes all words, and can also replace underscores with spaces, to transform it into a formatted title:</p><p>&quot;going_off_the_rails&quot;<strong>.</strong>titleize =&gt; &quot;Going Off The Rails&quot;</p><p>&quot;going off the rails&quot;<strong>.</strong>titleize =&gt; &quot;Going Off The Rails&quot;</p><p>The ActiveSupport::Inflector module has quite a few methods that are available for us to use, which you find more information about <a href="http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html">here</a>.</p><p>If it weren’t for running into SMOOTHY (smh), you might not assume we would ever need to worry about this issue, since the Rails magic works more often than not.</p><p>EnterSmoothies(which we know should be singularized as Smoothie) and another example, Octopus(which we all know should be pluralized as Octopodes).</p><p>&quot;smoothies&quot;<strong>.</strong>singularize =&gt; &quot;smoothy&quot;*</p><p>&quot;octopus&quot;<strong>.</strong>pluralize =&gt; &quot;octopi&quot; *</p><p>*these are just so wrong, we must fix it immediately.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3DtfI4yfJEZMY%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3DtfI4yfJEZMY%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3DtfI4yfJEZMY%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/a4a653efa68aa702f08e8f04e365d426/href">https://medium.com/media/a4a653efa68aa702f08e8f04e365d426/href</a></iframe><h3>Writing New Inflections</h3><p>Let’s first take a look at the ActiveSupport::Inflector module, and more specifically, the aptly named inflections method, which is what allows us to specify our own inflector rules.</p><h4>How it works:</h4><blockquote>A singleton instance of this class is yielded by <a href="http://api.rubyonrails.org/classes/ActiveSupport/Inflector.html#method-i-inflections">ActiveSupport::Inflector#inflections</a>, which can then be used to specify additional inflection rules. If passed an optional locale, rules for other languages can be specified.</blockquote><p>We write our own inflections inside of the config/initializers/inflections.rb file. This file is made upon a Rails new creation, and contains the following information:</p><pre># Be sure to restart your server when you modify this file.</pre><pre># Add new inflection rules using the following format. Inflections<br># are locale specific, and you may define rules for as many different<br># locales as you wish. All of these examples are active by default:<br># ActiveSupport::Inflector.inflections(:en) do |inflect|<br>#   inflect.plural /^(ox)$/i, &#39;\1en&#39;<br>#   inflect.singular /^(ox)en/i, &#39;\1&#39;<br>#   inflect.irregular &#39;person&#39;, &#39;people&#39;<br>#   inflect.uncountable %w( fish sheep )<br># end</pre><pre># These inflection rules are supported but not enabled by default:<br># ActiveSupport::Inflector.inflections(:en) do |inflect|<br>#   inflect.acronym &#39;RESTful&#39;<br># end</pre><p>We are given the appropriate information about how to start writing our own inflections with the examples in this file. In our case, we’re dealing with an irregular inflection where octopus needs to be pluralized as octopodes, and smoothies needs to be singularized as smoothie. So we’ll use the irregular method (which handles the singularization and pluralization), and it takes two arguments: the singular and the plural form of the word as strings.</p><pre>ActiveSupport::Inflector.inflections(:en) do |inflect|<br>  inflect.irregular &#39;octopus&#39;, &#39;octopodes&#39;<br>end</pre><pre>ActiveSupport::Inflector.inflections(:en) do |inflect|<br>  inflect.irregular &#39;smoothie&#39;, &#39;smoothies&#39;<br>end</pre><p>Now let’s test it out:</p><pre>&quot;octopus&quot;.pluralize =&gt; &quot;octopodes&quot;</pre><pre>&quot;smoothies&quot;.singularize =&gt; &quot;smoothie&quot;</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FToMjGpnXBTw7vnokxhu%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FToMjGpnXBTw7vnokxhu%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FToMjGpnXBTw7vnokxhu%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="262" frameborder="0" scrolling="no"><a href="https://medium.com/media/c17aed738a96e86f73dbab0d3fe57dcb/href">https://medium.com/media/c17aed738a96e86f73dbab0d3fe57dcb/href</a></iframe><p>We could also establish other rules for our app using any of the various other methods, such as: uncountable %w( money information rice ) which would specify words that should <em>not</em> be inflected since they are uncountable.</p><p>Our app now knows about the new rules that we laid out for it explicitly.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FgD4qsl8mOyQqk%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FgD4qsl8mOyQqk%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FgD4qsl8mOyQqk%2F200.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/48b032a69ff03a0a45496c073dabc4a7/href">https://medium.com/media/48b032a69ff03a0a45496c073dabc4a7/href</a></iframe><p>We can all rest easy knowing that our naming conventions are right. And now, the next time we run into a grammatical error or edge case, we can fix it in no time at all.</p><h3>The takeaway</h3><ul><li>ActiveSupport::Inflector handles the grammatical rules in Rails.</li><li>The inflections.rb file is where we are able to write our own inflection rules.</li><li>English is wild.</li><li>Check your language/naming in the Rails console to make sure you don’t run into any issues.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b36985a60aeb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[*SPLAT]]></title>
            <link>https://medium.com/@eanorton/splat-8edcb7bba54e?source=rss-4cbfd0c15542------2</link>
            <guid isPermaLink="false">https://medium.com/p/8edcb7bba54e</guid>
            <category><![CDATA[flatiron-school]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Edward Norton]]></dc:creator>
            <pubDate>Tue, 08 May 2018 02:56:02 GMT</pubDate>
            <atom:updated>2018-05-08T11:41:46.314Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>An overview of the single *Splat and double **Splat operators in Ruby</strong></p><p>As I enter the third week of Flatiron, I’ve found that on multiple occasions there have been times where I have been trying to define a method without knowing how many arguments it will take. From a bit of brief reading, I knew about the splat operator, but I still felt that the extent of its functionality eluded me. So I decided to take a closer look.</p><h4><strong>Single *Splat</strong></h4><p>You can apply a splat in two ways, depending where/how it’s used:</p><ul><li>You can use * to coerce a number of arguments into an array.</li><li>You can also use * to split up an array into an argument list.</li></ul><p>When creating a method, you use the splat operator in the definition, and the result is that the method accepts any number of arguments. The complete argument list will be passed as an array.</p><pre>def thats_a_good_looking_list(*args)<br>  args.each.with_index(1){|element, i| puts &quot;#{i}. #{element}&quot;}<br>end</pre><pre>thats_a_good_looking_list(&quot;The&quot;, &quot;More&quot;, &quot;You know&quot;)</pre><pre># 1. The<br># 2. More<br># 3. You know<br># =&gt; [&quot;The&quot;, &quot;More&quot;, &quot;You know&quot;]</pre><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3og0IMJcSI8p6hYQXS%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3og0IMJcSI8p6hYQXS%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F3og0IMJcSI8p6hYQXS%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="322" frameborder="0" scrolling="no"><a href="https://medium.com/media/e8c1b30649ed17863e05fa5c6a03ba9c/href">https://medium.com/media/e8c1b30649ed17863e05fa5c6a03ba9c/href</a></iframe><p>The second option of using a splat would be when you consider the following method:</p><pre>def basic_addition_for_lazy_people_like_me(x, y, z)<br>  x + y + z<br>end</pre><p>You can now call the method:</p><pre>my_array_of_basic_nums = [2, 4, 6]<br>basic_addition_for_lazy_people_like_me(*my_array_of_basic_nums)</pre><pre># =&gt; 12</pre><p>But without using the splat, you would simply get:</p><pre>my_array_of_basic_nums = [2, 4, 6]<br>basic_addition_for_lazy_people_like_me(my_array_of_basic_nums)</pre><pre># =&gt; ArgumentError: wrong number of arguments (given 1, expected 3)</pre><p>The splat can be used to split and pass each element of the array as an individual parameter to the method. You could do the same even by calling thats_a_good_looking_list:</p><pre>thats_a_good_looking_list(*my_array_of_basic_nums)<br># 1. 2<br># 2. 4<br># 3. 6<br># =&gt; [2, 4, 6]</pre><p>You can also use the splat operator to grab any segment of an array:</p><pre>the_more, *the_less, you_know = [&quot;hello&quot;, &quot;just testing&quot;, &quot;how&quot;, &quot;this&quot;, &quot;works&quot;]</pre><pre>the_more <br># =&gt; &quot;hello&quot;</pre><pre>the_less <br># =&gt; [&quot;just testing&quot;, &quot;how&quot;, &quot;this&quot;]</pre><pre>the_less[1] <br># =&gt; &quot;how&quot;</pre><pre>you_know <br># =&gt; &quot;works&quot;</pre><h4><strong>Double **Splat</strong></h4><p>It’s similar to the single splat, but with a “key” difference…</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F10GUbOX16lS15C%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F10GUbOX16lS15C%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F10GUbOX16lS15C%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="387" frameborder="0" scrolling="no"><a href="https://medium.com/media/17444d893bb8ede684f80877dbd87b0e/href">https://medium.com/media/17444d893bb8ede684f80877dbd87b0e/href</a></iframe><p>The double splat is used for hashes!</p><p>Here’s the out output of a double splat:</p><pre>def dubsplat(**args)<br>  p **args<br>end </pre><pre># =&gt; {}</pre><p>Expanding on it:</p><pre>def splatsplat(**args)<br>  p **args<br>end</pre><pre>splatsplat(the_more: &quot;you know&quot;)</pre><pre># =&gt; {the_more=&gt;&quot;you know&quot;}</pre><pre>splatsplat(the_more: &quot;you know&quot;, the_less: &quot;you don&#39;t know&quot;, but_either_way: &quot;this hash can be as long as you want&quot;, so_thats_neat: &quot;i guess&quot;)</pre><pre># =&gt; {:the_more=&gt;&quot;you know&quot;, :the_less=&gt;&quot;you don&#39;t know&quot;, :but_either_way=&gt;&quot;this hash can be as long as you want&quot;, :so_thats_neat=&gt;&quot;i guess&quot;}</pre><p>When using the double splat, it allows you to capture an indefinite number of keyword arguments, and that’s pretty neat.</p><h3><strong>The Takeaway</strong></h3><p>The main thing to keep in mind when using the *splat operator in Ruby is that you use splats as a parameter in a method when you don’t know how many arguments your method will be using, and you can use it to coerce arguments into an array or to split an array into an argument list.</p><p>The double ** works in a similar way to the single * — it captures all keyword arguments, but instead of an array, its functionality is applied to working with hashes.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8edcb7bba54e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Classes vs. Modules]]></title>
            <link>https://medium.com/@eanorton/classes-vs-modules-7140f31d9104?source=rss-4cbfd0c15542------2</link>
            <guid isPermaLink="false">https://medium.com/p/7140f31d9104</guid>
            <category><![CDATA[flatiron-school]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Edward Norton]]></dc:creator>
            <pubDate>Sun, 15 Apr 2018 19:45:11 GMT</pubDate>
            <atom:updated>2018-04-17T16:43:19.426Z</atom:updated>
            <content:encoded><![CDATA[<h4>What the heck is the difference?</h4><p>I asked myself before writing this post if I could describe the differences between classes and modules to someone, and I found that I couldn’t give a very clear explanation. So I thought I would use this first blog post as a way to clear some things up for myself, and hopefully for a few others as well.</p><p>After my extensive research (OK, Google!), I found that the differences can be boiled down to a few basic ideas:</p><ul><li>Modules don’t have instances. So it would follow that an entity or object, would generally be best modeled in a class, and the <em>characteristics or properties of that thing </em>should be encapsulated in a module. Thus, class names tend to be nouns, and module names are often adjectives.</li><li>Another important point is that a class can have only one superclass, but it can mix in as many modules as it wants. So, if you’re using inheritance, you should probably give priority to creating a sensible superclass/subclass relationship — it would be best to not use up a class’ one and only superclass relationship to provide the class with what might turn out to be just one of several sets of properties.</li></ul><p><strong>Example of what NOT to do:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/069454def1bb2e774a496a6c6948d3e7/href">https://medium.com/media/069454def1bb2e774a496a6c6948d3e7/href</a></iframe><p><strong>Example of what you SHOULD do:</strong></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/52ec52dcd6199b324ffa47ed3adbce6f/href">https://medium.com/media/52ec52dcd6199b324ffa47ed3adbce6f/href</a></iframe><p>The second version models the entity and the property more neatly. Car descends from vehicle (which makes sense). Whereas power steering is a characteristic of a vehicle — at least, the ones we care about for the sake of the example — a characteristic that is passed on to cars by virtue of car being a descendant of vehicle.</p><p>It’s good to know the differences when it comes to modeling things for ourselves, and having a better idea of when and how we can demonstrate the characteristics our classes possess.</p><p><strong>Let’s take this further:</strong></p><p>Imagine we are trying to write program that can build humans, but not just any kind of human, we want to build people who have the ability to play tennis.</p><p>First we’ll have to make our Human class, and luckily from those two bio classes in college, and with the help of Wikipedia, we know all the important parts we’ll need in order to make some brand new human beings.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59efe67ef6ab2a0fa3e32e2c91af9ebd/href">https://medium.com/media/59efe67ef6ab2a0fa3e32e2c91af9ebd/href</a></iframe><p>Regardless of whatever class we build that descends from Human, it can inherit the methods from the Human class. In other words, it would be bipedal, have a larger brain, and it would have to eat food since it can’t produce it’s own nutrients.</p><p>But we want to make humans who can play tennis, so obviously they’ll have to be athletes</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/05d726318d0ff99bdb2db3d21e2d6aa2/href">https://medium.com/media/05d726318d0ff99bdb2db3d21e2d6aa2/href</a></iframe><p>Our Athlete class descends from the Human class, and in addition to being bipedal and having bigger brains, they call the methods in Athlete, such as being fit and super competitive!</p><p><strong>Tennis Humans</strong></p><p>roger_federer = Athlete.new</p><p>serena_williams = Athlete.new</p><p>Roger and Serena are both athletes, so in addition to both needing to eat and being bipedal, they’re competitive and super fit because they are both from the Athlete class, which has inherited methods from the Human class.</p><p>Our brand new athletes, Roger and Serena, are kids and both have an interest in tennis. Luckily for them there just so happens to be a module which has the ability to endow a class — in this case, Athletes — with the ability to play tennis <em>really</em> well… So let’s go ahead and bestow upon them some supernatural skills.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5e18724e69da6ccb0514b9699dac9763/href">https://medium.com/media/5e18724e69da6ccb0514b9699dac9763/href</a></iframe><p>Now when we include the SupernaturalTennisSkills module in our Athlete class, Roger and Serena can dominate the game of tennis! (It’s that easy, right?)</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6cf93c7223c91aa919455a7438518d7/href">https://medium.com/media/c6cf93c7223c91aa919455a7438518d7/href</a></iframe><p>Roger Federer and Serena Williams are both still athletes, but now they have all of the amazing supernatural tennis skill methods! THWACK!</p><p>What’s more, if you really wanted, you could create a new class — let’s say class WebDeveloper — and you could include the tennis skills module, and you could have a whole bunch of devs serving up aces!</p><h4>To sum up</h4><p>Classes and modules are extremely similar. When translating real world ideas into code, we need to think through what characteristics we want classes to inherit and what we can include with the use of modules. So modules are for sharing behavior, while classes are for modeling the actual relationships between objects.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7140f31d9104" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>