<?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 Jeremy Lenz on Medium]]></title>
        <description><![CDATA[Stories by Jeremy Lenz on Medium]]></description>
        <link>https://medium.com/@jeremylenz?source=rss-80b960c985f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*vJsCJ8NC0Urp6FySTVK2hQ.jpeg</url>
            <title>Stories by Jeremy Lenz on Medium</title>
            <link>https://medium.com/@jeremylenz?source=rss-80b960c985f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 30 May 2026 05:38:57 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@jeremylenz/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[When Active Record is too slow]]></title>
            <link>https://medium.com/@jeremylenz/when-active-record-is-too-slow-588f5399b545?source=rss-80b960c985f------2</link>
            <guid isPermaLink="false">https://medium.com/p/588f5399b545</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[activerecord]]></category>
            <category><![CDATA[hash]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[performance]]></category>
            <dc:creator><![CDATA[Jeremy Lenz]]></dc:creator>
            <pubDate>Wed, 20 Feb 2019 23:16:41 GMT</pubDate>
            <atom:updated>2019-02-20T23:16:41.776Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been doing quite a bit of work lately on the Rails API for <a href="https://github.com/jeremylenz/busrate">BusRate</a>, my personal project around measuring performance of NYC buses. Having a project that adds over 1 million rows to the database per day has really been teaching me a lot. When your RAM fills up and the OS starts killing processes, or your disk fills up, it really has a way of getting your attention! So the more I can do to speed things up and use fewer resources, the better.</p><p>Anyway, as part of a new feature I’ve been building, there’s a method called aggregate_trip_view. What does it do? It doesn’t really matter. The point is, there’s a loop in there where one of the steps is</p><pre>bus_line = BusLine.find_by(line_ref: line_ref)</pre><p>I had noticed this particular method was pretty slow. I had put some timers in the logs, and was getting results like</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*M9u2FiFZxoiRexZkmCuRTg.png" /></figure><p>7.63 seconds… Why was looking up BusLines so slow? I had a theory, since I’ve come across something similar on this project before.</p><p>To test it, I ran</p><pre>Rails.logger.level = 0</pre><p>This set the logger to `DEBUG` level so that I could see every database query.</p><p>And sure enough,</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*vteV5kT3gjMaoqU9d1Ngig.png" /></figure><p>Rails was running a different SQL query every time I looked up a BusLine. I only have 334 BusLines in the database, but since it’s a separate query for each one, it adds up fast!</p><p>So, how to solve it? Of the very few things I know about computer science, one of them is: <em>Hash maps are fast.</em> So I decided to try using a Ruby hash to help me out.</p><p>Instead of using Rails Active Record to look up 334 individual BusLines, I refactored the method like so:</p><pre># Outside the loop<br>bus_lines = BusLine.all.each_with_object({}) do |bus_line, bus_lines_obj|<br>  bus_lines_obj[bus_line.line_ref] = bus_line<br>end</pre><p>This uses <a href="https://medium.com/@jeremylenz/rubys-each-with-object-method-f0784bdefb3c">each_with_object</a> and makes a hash (Ruby object) where the <em>key</em> is the line_ref (bus line ID), and the <em>value</em> is the individual BusLine instance. The upside of this is that it’s only one single SQL query (SELECT * FROM bus_lines) instead of 334!</p><p>Now, inside the loop, I can look up the BusLines much more quickly, like so:</p><pre># inside the loop<br>bus_line = bus_lines[line_ref]</pre><p>And sure enough, the results were much better!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XuLKTFmCTX_bCu2RSnVoQA.png" /></figure><p>Over 7 seconds down to 0.05. Not bad!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=588f5399b545" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Using JavaScript Sets in a Redux Store]]></title>
            <link>https://medium.com/@jeremylenz/using-javascript-sets-in-a-redux-store-5ea10e882719?source=rss-80b960c985f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ea10e882719</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[data-structures]]></category>
            <dc:creator><![CDATA[Jeremy Lenz]]></dc:creator>
            <pubDate>Wed, 28 Nov 2018 18:25:56 GMT</pubDate>
            <atom:updated>2018-11-28T18:25:56.103Z</atom:updated>
            <content:encoded><![CDATA[<p>In writing my latest side project, which has a front-end written in React &amp; Redux, I made a cute little CSS loader/spinner so that my users would know when I’m waiting to get data back from my API. I carved out a part of the Redux store to keep track of the state of my API requests. Originally, it was pretty simple:</p><pre><br>ui: {<br> loading: true,<br> feature: ‘BusLines’<br>}<br></pre><p>When loading is true, my React component would display the spinner. When loading changed to false, the component would see that and remove the spinner. The feature key is just so I would know which type of data I was waiting on (I have a few, including BusLines, RealTimeData, and HistoricalDepartures.) And of course, this worked great! Until it didn’t.</p><p>My spinners worked, but they always seemed to be disappearing too soon. I would see the component appear with blank data, and then the data would populate a second or two later. Why was this happening?</p><p>You may already see the problem: What if we’re loading more than one type of data at once?</p><p>The request would start for RealTimeData but I would also need some HistoricalDepartures. Now both requests are pending at once. When the <em>first</em> one comes back, it was setting the loading flag to false, causing my spinner to disappear prematurely.</p><p>At this point it was getting more and more apparent that I needed a better solution. Once you have more than one type of data, it’s not enough to keep track of whether I’m loading something. I also need to know <em>what</em> is loading, and be able to handle <em>multiple</em> things loading at the same time. So what should our little corner of the Redux store look like?</p><p>The first solution I was thinking about looked something like this:</p><pre><br>ui: {<br> loading: true,<br> features: [‘BusLines’, ‘HistoricalDepartures’]<br>}<br></pre><p>Here we use an array to store which features are loading. That way, I’d be able to keep track of the loading state of multiple features and not just one. But what do we do when, say, the BusLines request comes back and is no longer loading?</p><pre><br># ui.reducer.js</pre><pre>let newFeatures = ui.features.filter((feature) =&gt; feature !== ‘BusLines’)<br>let newLoading = (ui.features.length === 0)<br></pre><p>This works just fine. Now what if BusLines is still loading, but we also just started loading RealTimeData?</p><pre><br>if (!ui.features.includes(‘RealTimeData’)) {<br> newFeatures.push(‘RealTimeData’)<br>}</pre><p>Also works okay, but it’s just a bit inelegant. After all, we have to iterate through the whole array just to make sure we’re not duplicating elements.</p><p>In the end, instead of an array I decided to use Sets to solve the problem. I think Sets are a perfect solution for this situation.</p><p>So now our corner of the Redux store looks like this:</p><pre><br># default state<br>ui: {<br> loading: true,<br> features: new Set()<br>}<br></pre><p>Now, I can do this</p><pre><br>features.add(‘RealTimeData’)<br></pre><p>as many times as I want, and the Set won’t have any duplicates.</p><p>I can check for elements like this:</p><pre>if (features.has(‘RealTimeData’)) {…}</pre><p>I can remove elements like this:</p><pre>features.delete(‘RealTimeData’)</pre><p><em>(Note: This will work even if the set doesn’t include that element. It won’t throw an error; it will just return </em><em>false instead of </em><em>true.)</em></p><p>A couple caveats (don’t worry, they’re not too bad):</p><ul><li>Sets are part of JavaScript ES6, so they can’t be used in older JavaScript versions.</li><li>If you use Redux Devtools extension, the value of the set doesn’t display properly in the extension. But rest assured it’s storing the data just fine. You can confirm this by doing some console.logs, which are actually kind of fun to watch:</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/796/1*Tde4gOHFGm4R4YsS47DO2Q.png" /></figure><p>After implementing my loader state as a Set instead of an Array, it worked perfectly. Try it out next time you need to store some unique values and you don’t care about the order!</p><p><em>More info:</em> <a href="https://alligator.io/js/sets-introduction/">https://alligator.io/js/sets-introduction/</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ea10e882719" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Why I love Ruby: An example]]></title>
            <link>https://medium.com/@jeremylenz/why-i-love-ruby-an-example-8047e3af1415?source=rss-80b960c985f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8047e3af1415</guid>
            <category><![CDATA[simplicity]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[coding]]></category>
            <dc:creator><![CDATA[Jeremy Lenz]]></dc:creator>
            <pubDate>Tue, 21 Aug 2018 16:34:33 GMT</pubDate>
            <atom:updated>2018-08-21T16:34:33.115Z</atom:updated>
            <content:encoded><![CDATA[<p>I was having fun doing an easy HackerRank <a href="https://www.hackerrank.com/challenges/birthday-cake-candles/problem">challenge</a> this morning. (The gist of the problem is, given an array like [4, 4, 3, 1, 2], return the number of times the maximum value occurs — in this case, 4 occurs twice so I would return 2.)</p><p>JavaScript:</p><pre>function birthdayCakeCandles(ar) {</pre><pre>  var max = ar.reduce(function(a, b) {</pre><pre>  return Math.max(a, b);</pre><pre>  });</pre><pre>  var count = 0;</pre><pre>  for (var i = 0; i &lt; ar.length; i++) {</pre><pre>    if(ar[i] === max) {</pre><pre>    count++;</pre><pre>    }</pre><pre>  };</pre><pre>  return count;</pre><pre>}</pre><p>Ruby:</p><pre>def birthday_cake_candles(ar)</pre><pre>  ar.count(ar.max)</pre><pre>end</pre><p>Both of these solutions do exactly the same thing. It’s striking and just a little bit hilarious how much more elegant and simple Ruby is.</p><p>(If you have a one-line JavaScript solution that I’m missing, I’d love to see it!)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8047e3af1415" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[If you’re using Atom with Rubocop and you have git pre-commit hooks that run it before it lets you…]]></title>
            <link>https://medium.com/@jeremylenz/if-youre-using-atom-with-rubocop-and-you-have-git-pre-commit-hooks-that-run-it-before-it-lets-you-ed32f0e1c4ea?source=rss-80b960c985f------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed32f0e1c4ea</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[atom]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jeremy Lenz]]></dc:creator>
            <pubDate>Fri, 08 Jun 2018 14:59:59 GMT</pubDate>
            <atom:updated>2018-06-08T14:59:59.485Z</atom:updated>
            <content:encoded><![CDATA[<h3>If you’re using Atom with Rubocop and you have git pre-commit hooks that run it before it lets you commit anything and you recently installed an old Ruby with RVM and now git commits work on the command line but not in Atom</h3><p>… Install this Atom package here. It fixed it for me!</p><p><a href="https://atom.io/packages/000-project-shell-env">000-project-shell-env</a></p><p>It’s something to do with environment variables. The related Github issue is here: <a href="https://github.com/atom/github/issues/764">https://github.com/atom/github/issues/764</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed32f0e1c4ea" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Making an OAuth 1.0 signature for Twitter]]></title>
            <link>https://medium.com/@jeremylenz/making-an-oauth-1-0-signature-for-twitter-4040dc30776?source=rss-80b960c985f------2</link>
            <guid isPermaLink="false">https://medium.com/p/4040dc30776</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[twitter]]></category>
            <category><![CDATA[cryptography]]></category>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[oauth]]></category>
            <dc:creator><![CDATA[Jeremy Lenz]]></dc:creator>
            <pubDate>Sun, 24 Dec 2017 19:31:03 GMT</pubDate>
            <atom:updated>2017-12-24T19:31:03.734Z</atom:updated>
            <content:encoded><![CDATA[<p>Merry Christmas! Your Christmas present is a blog post on how to make an OAuth 1.0 signature for sending requests to Twitter’s API.</p><p>Basically we have to do three things:</p><ol><li>Gather our data</li><li>Prepare and assemble the data</li><li>Encrypt the data</li></ol><p>Sounds simple, right? As usual, no. Welcome to OAuth 1.0.</p><h3>Gather data</h3><p>This is the simplest part. We need the following stuff to be part of the signature:</p><ul><li>The HTTP method (usually ‘POST’)</li><li>The URL we’re sending the request to</li><li>oauth_consumer_key: Our Twitter API key</li><li>oauth_nonce: A string value which uniquely identifies the request</li><li>oauth_signature_method: ‘HMAC-SHA1’ is the hashing algorithm which is used to encrypt the signature. Ironically, we have to tell Twitter that we’re using HMAC-SHA1 to encrypt the signature, but this information can only be viewed after decrypting. Okay.</li><li>oauth_timestamp: The number of seconds that have elapsed since 00:00:00 Coordinated Universal Time (UTC), Thursday, January 1, 1970, minus the number of leap seconds that have taken place since then. Don’t ask.</li><li>oauth_token: The access token we got from Twitter (see the previous post)</li><li>oauth_verson: ‘1.0’</li><li>In addition to these key-value pairs, we also must include any other key-value pairs we’re sending as part of the request.</li></ul><h3>Prepare and assemble the data</h3><p>For each of the key-value pairs above, we have a list of stuff we have to do:</p><ol><li><strong>Percent-encode</strong> it. <a href="https://developer.twitter.com/en/docs/basics/authentication/guides/percent-encoding-parameters.html">This</a> is Twitter’s doc explaining percent-encoding in detail. Long story short, we turn a string like</li></ol><p>Dogs, Cats &amp; Mice</p><p>into something like this:</p><p>Dogs%2C%20Cats%20%26%20Mice</p><p>2. <strong>Sort</strong> the list alphabetically by key, <strong>except</strong> that the HTTP Method and URL go first.</p><p>3. Assemble the string according to the format “key=value&amp;key=value” (except that HTTP Method and URL don’t include key=)</p><p>Once that’s done, we have a <strong>Signature Base String</strong>.</p><h3>Encrypt the data</h3><p>In order to take the parameter string and turn it into a signature, we need to get a <strong>Signing Key.</strong> This is done by assembling two values, the Consumer Secret (Twitter API key) and OAuth token secret, if we have one (obtained from Twitter by doing the sign-in dance explained in the last post). The Signing Key is assembled using the format “value&amp;value” (or, if we don’t have an OAuth Token Secret yet, just “value&amp;”.) (By the way, we also have to <strong>percent-encode</strong> these before assembling them.)</p><p>Now that we have our Signature Base String and Signing Key, there are only a couple steps left!</p><ol><li>Encrypt the Signature Base String with HMAC-SHA1, using the Signing Key as our encryption key. This will give us a binary string, something like<br>84 2B 52 99 88 7E 88 7602 12 A0 56 AC 4E C2 EE 16 26 B5 49</li><li>Encode the encrypted string using Base64. This will turn it into something like<br>hCtSmYh+iHYCEqBWrE7C7hYmtUk=</li></ol><p>And we’re done! That’s our Signature.</p><p>By the way, the values used above are example values from Twitter’s documentation. This is the <em>only way </em>Twitter gave me to test if my code is working correctly. Using the example values from <a href="https://developer.twitter.com/en/docs/basics/authentication/guides/creating-a-signature.html">Twitter’s document</a>, if you do all the steps correctly, you should end up with the signature above. If you get <em>even one</em> parameter incorrect, or leave out one key-value pair, you’ll end up with a completely different signature and Twitter will reject your request. In that case, there are no error messages to help you find where you’re going wrong. Twitter will just send back a cryptic error. You just have to think a lot and keep trying. (Note: Make sure your signature base string doesn’t have any leading or trailing spaces. That one took a while for me to catch.)</p><p><em>Thanks to Wikipedia for the definition of </em><a href="https://en.wikipedia.org/wiki/Unix_time"><em>Unix epoch</em></a><em>.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4040dc30776" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Implementing Sign in with Twitter from scratch]]></title>
            <link>https://medium.com/@jeremylenz/implementing-sign-in-with-twitter-from-scratch-5ae8afb9cc5f?source=rss-80b960c985f------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ae8afb9cc5f</guid>
            <category><![CDATA[problem-solving]]></category>
            <category><![CDATA[oauth]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Jeremy Lenz]]></dc:creator>
            <pubDate>Sun, 29 Oct 2017 19:10:41 GMT</pubDate>
            <atom:updated>2017-10-29T19:10:41.912Z</atom:updated>
            <content:encoded><![CDATA[<p>When I made my final project for Flatiron School, <a href="https://bikeways.herokuapp.com/">Bikeways</a>, having Sign in with Twitter available was very important to me because the #bikeNYC community has a very active, lively Twitter presence. I didn’t know it when I started, but getting it working became one of the biggest challenges I had to overcome on the project.</p><p>To implement Sign in with Twitter, Twitter requires that I use <strong>OAuth</strong>. The benefit of using OAuth is that my app doesn’t need to know your Twitter password, but you can still use your Twitter credentials to log in. However, for whatever reason, Twitter is still using OAuth 1.0a for this process, not the newer OAuth 2.0. This means we have to do a very intricate dance of AJAX requests between my app and Twitter’s API:</p><ol><li>Send a signed POST request to api.twitter.com/oauth/request_token. This request contains a callback_url, which Twitter will use later in Step 4. If everything goes OK, Twitter will respond with a <strong>token</strong> and <strong>token secret</strong>.</li><li>At this point, my ‘Login with Twitter’ button becomes available. When it’s clicked, the user is directed to api.twitter.com/oauth/authenticate, and the <strong>token</strong> from Step 1 is included in the URL parameters.</li><li>Now, Twitter will handle the login. If the user hasn’t already authorized my app, Twitter will display its login screen and the user can enter credentials. If that’s done already, Twitter will just skip to the next step.</li><li>Once login is complete, Twitter will actually redirect the user back to my app’s callback_url, which I specified in Step 1. The URL parameters Twitter sends me will contain the same oauth_token I got back in Step 2, and an oauth_verifier which I can use in the next step.</li><li>When I get this response back, I must send another signed POST request, this time to api.twitter.com/oauth/access_token. The request will contain the oauth_verifier I obtained in the previous step.</li><li>If the planets are aligned properly, I’ll finally get an oauth_token_secret in the response. This is my digital wristband that proves that I’ve been admitted to the party. I should be able to use the oauth_token_secret for future Twitter API requests without having to do this dance again.</li></ol><p>Think that’s enough complication? Not even close. There are at least 3 things that add complication to this process:</p><ol><li>All the parameters must be <a href="https://developer.twitter.com/en/docs/basics/authentication/guides/percent-encoding-parameters"><strong>percent encoded</strong></a>, <em>properly</em>, or it won’t work.</li><li>All the requests I send to Twitter must be <strong>signed</strong>. A signature is a long string containing all the other parameters of the request, percent encoded, sorted in a specific way, and then encrypted using HMAC-SHA1. Maybe I’ll go into more detail about that in a future blog post.</li><li>If I get something wrong, Twitter’s API responses are quite opaque. They definitely don’t help much.</li></ol><p>I handled most of this using my Ruby on Rails backend, though of course my React front-end had to handle the part where Twitter redirects the user back to my app. I was able to pull out the URL params using the React Router location props, which I mentioned in my previous post.</p><p>Here are the three main Twitter documents I used, that explain all of this in excruciating detail:</p><p><a href="https://dev.twitter.com/web/sign-in/implementing">Implementing Sign in with Twitter</a></p><p><a href="https://developer.twitter.com/en/docs/basics/authentication/guides/creating-a-signature.html">Creating a signature</a></p><p><a href="https://developer.twitter.com/en/docs/basics/authentication/guides/authorizing-a-request">Authorizing a request</a></p><p>I did use the <a href="https://rubygems.org/gems/oauth/versions/0.5.1">Ruby OAuth gem</a>, but only for the OAuth::Helper methods to percent encode my strings properly. (I also used its parse_header method to turn the incoming params into a hash.) But that’s it. I didn’t use any of its built-in methods for creating signatures or obtaining tokens. This is partly because I found the documentation difficult to understand, and partly because I knew it would be a great learning exercise to do it all manually.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ae8afb9cc5f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React Router basics: What I wish they’d told me]]></title>
            <link>https://medium.com/@jeremylenz/react-router-basics-what-i-wish-theyd-told-me-37b29201d40a?source=rss-80b960c985f------2</link>
            <guid isPermaLink="false">https://medium.com/p/37b29201d40a</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[react-router-4]]></category>
            <category><![CDATA[react-router]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <dc:creator><![CDATA[Jeremy Lenz]]></dc:creator>
            <pubDate>Sun, 22 Oct 2017 14:04:52 GMT</pubDate>
            <atom:updated>2017-10-25T22:00:34.766Z</atom:updated>
            <content:encoded><![CDATA[<p>Okay, so here’s my problem with React Router:</p><p>Like, don’t get me wrong — it’s great. You can put your routes in just like any other React components, you can nest them, the design is elegant, and in an ideal world, it “just works.’ But… The documentation leaves a lot to be desired. It seems like they make simple tasks feel complex. I’m working on a project using React Router this week. The last time I used it was several weeks ago, so naturally I needed a little refresher. I just had some basic questions, like:</p><p><em>How do I prevent my entire app from remounting?<br>I don’t want anything fancy. I just want to say, ‘If the user goes here, render this.’ How do I make simple routes that make sense?<br>How do I prevent React Router from matching multiple routes and rendering too many components?<br>How do I make my NavBar work right?<br>How do I make buttons work well for navigation?</em></p><p>I had a lot more trouble answering these than I feel like I should. So I thought I’d write this post in the hopes it helps some React Router beginners like me. Here’s a few things I’ve learned:</p><p><strong>If you use the URL bar in the browser, your entire app will re-render. </strong>The consequence of this is that your app state will be obliterated, including any data you had loaded. At first this threw me off a little, but it makes sense. If you type an address and press enter, your browser does a new GET request, and there’s probably no getting around that. (If there’s something I’m missing there, I’d love to be corrected!) So how to get around this? So far I’ve found two ways: First, use the &lt;Link&gt; component provided by React Router, instead of regular &lt;a&gt; tags. I’m not really sure how they differ, but it seems to prevent the app from reloading. But what if you want to have a &lt;button&gt; such as ‘Create User’ that takes you to a different page? I don’t know how ‘correct’ this is, but what I’ve been doing is</p><ol><li>Have an onClick event handler for the button which sets a redirect flag to true.</li><li>In the component’s render method, check if redirect is true. If so, render a &lt;Redirect /&gt; which is a component provided by React Router that will send you to whatever route you specify.</li><li>After this is complete, you have to remember to set the redirect flag back to false, or else you’ll be caught in an infinite loop. I think React’s componentDidUpdate lifecycle method seems like a good place to do this.</li></ol><p><strong>Update</strong>: None of the above is necessary. I found out that this.props.history.push is a great way to get your buttons to work right! You just have to use it in conjunction with withRouter, explained below.</p><p>Another thing beginners like me have trouble with is the <strong>React Router v4 philosophy. </strong>Instead of thinking in terms of simple routes, you’re supposed to think in a more complex way about how you want your app to display. The basic idea is conditional rendering: Given any Route, if the path matches, render the component. If the path doesn’t match, don’t render it. That means that React Router does some things you may not expect.</p><p>For example, let’s say you have a group of routes like this:</p><p>&lt;Route path=‘/users’ component={UserList} /&gt;<br>&lt;Route path=‘/accounts’ component={accounts} /&gt;<br>&lt;Route exact path=‘/users/delete’ component={DeleteUserForm} /&gt;</p><p>If the user navigates to /users/delete, which components get rendered? You may think it’s just DeleteUserForm, but you’d be surprised. Both /users and /users/delete contain the string ‘/ users’, so this would match both Routes and both components would be displayed. This is true even though the DeleteUserForm specifies the ‘exact’ prop. Exact <em>doesn’t prevent other Routes from being rendered </em>— it just prevents that <em>specific</em> Route from rendering <strong>if</strong> it’s not an exact match. Thus, if the user goes to /users, only UserList would be rendered because ‘/users’ is not an exact match for /users/delete. But if you navigate to /users/delete, both routes match.</p><p>(By the way, to make React Router behave a little closer to standard expectations, you can enclose a group of Routes inside a &lt;Switch&gt;. React Router will render <em>only</em> the first Route that matches, and will ignore any subsequent routes in the Switch.)</p><p>To add even more complexity, here’s something else to think about: I’ve been saying certain things ‘don’t render,’ but that’s actually not the case. React Router actually renders every Route, every time. It just renders null if it’s not a match.</p><p>Ok, one more thing: React Router gives its Routes some handy props that give you some useful information:</p><p><strong>match</strong>: How we got here. this.props.match.path contains the url that was actually navigated to. match.params contains any URL parameters (the stuff in the URL after the ?.)</p><p><strong>location</strong>: Where we are now. this.props.location.pathname contains your current location.</p><p><strong>history</strong>: The complete history object.</p><p>The thing to remember about this is, <strong>only the Routes</strong> get these props. Your other components won’t have them. But what if we want that info to be available to, say, a NavBar so we can keep track of where we are? To do this, React Router includes the withRouter method. It’s easy to use. Say you have a NavBar React component, declared as an ES6 class:</p><p>class NavBar extends React.Component { … }<br>export default NavBar</p><p>All you have to do is wrap it in WithRouter, like so:</p><p>export default <strong>withRouter</strong>(NavBar);</p><p>Oh, and don’t forget to import { withRouter } from ‘react-router-dom’</p><p>Now, your NavBar component will have those props.</p><p>Hopefully this post will be helpful to some React Router beginners like me. If you have any tips to share I’d love to hear them!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=37b29201d40a" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 Things I Learned from Doing Group Programming Projects]]></title>
            <link>https://medium.com/@jeremylenz/5-things-i-learned-from-doing-group-programming-projects-794aa6d9128?source=rss-80b960c985f------2</link>
            <guid isPermaLink="false">https://medium.com/p/794aa6d9128</guid>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[bootcamp]]></category>
            <category><![CDATA[flatiron-school]]></category>
            <category><![CDATA[group-dynamics]]></category>
            <category><![CDATA[personal-growth]]></category>
            <dc:creator><![CDATA[Jeremy Lenz]]></dc:creator>
            <pubDate>Wed, 30 Aug 2017 18:27:49 GMT</pubDate>
            <atom:updated>2017-08-30T18:27:49.674Z</atom:updated>
            <content:encoded><![CDATA[<p>When reading articles on the Internet, have you noticed that usually you can skip the first two paragraphs or so and you’ll be just fine? The fact is, the first two paragraphs are mostly just drivel designed to avoid the awkwardness (and reduced ad revenue) of getting to the point of your article right away.</p><p>If those two paragraphs weren’t there, I guess the article or blog post would feel a bit weird, but 99% of the time I find myself skimming right over that part of the page anyway. Especially with clickbait headlines, the “answer” to the question doesn’t present itself until a little farther down, and with experience it’s easy to make educated guesses as to where that answer is and just jump right there.</p><h3>Scoping is hard</h3><p>Before you start your project, you think things like “I can easily finish authentication, 16 models, 9 pages, and 3 API integrations in 3 days!” Then you learn that this is not the case. I feel like it’s going to take me several more projects before I’m good at accurately estimating how long things are going to take. I’m happy that instructors are going to help us with scoping our final projects, which are longer than anything we’ve done up to this point.</p><h3>It’s a project, not a product</h3><p>It’s easy to think that your project has to be an amazing business idea. It has to have a great domain name, you should think about how to market it, you have to consider how well it will scale, if it’s been done before, network effects, customer acquisition, etc. NO! Your project is a project, not a product. Unless you’re here in between semesters at business school (sorry, Paul) the point of doing a project is to show your proficiency in Rails, or React, or JavaScript, or Ruby — in other words, to showcase your skills as a developer. During our limited time here, it’s best to keep that technical focus. There’s nothing wrong with great business ideas, but I feel like they can wait until you have more time.</p><h3>It does matter how it looks</h3><p>With that said, the other side of the coin is that appearances ARE important. You can have an amazing back-end with some Einstein-level logic happening, but if your site looks like it’s from 1995, it’s just not going to be as impressive. There are a ton of CSS and other frameworks out there (Bootstrap, Materialize, Semantic) which make it REALLY easy to make your project look decent, fast. And it’s totally worth it to put in the time to implement one of them. In my experience, it actually makes a HUGE difference in how impressed people are with your project. If you take the time to make your project look great, people will appreciate all your hard work on the back-end logic. If you don’t, they won’t. It may sound harsh, but it’s the truth.</p><h3>It makes it click</h3><p>Over the past twelve weeks, we’ve become all too familiar with the Flatiron School process of Learning a New Thing:<br>1. Do a bunch of labs on Learn.co. Barely grasp the concepts. (#$%^&amp; tests!!)<br>2. Listen to lectures. Seems easy.<br>3. Try to do it. Nope.. it’s hard.<br>4. Repeat steps 1–3 for two weeks.</p><p>But then when you get into Project mode, it all changes. Project mode is when you actually get a lot of practice doing the new thing. A lot of the time, it’s also when the new concept finally ‘clicks’ for me. By the end of my project, I actually feel confident using my new knowledge. I feel ready to take the code challenges. And I feel like I could do it all again and not make all the rookie mistakes.</p><h3>You see your dark side</h3><p>Project mode is when you can have some of your most challenging moments. I spent a LOT of time frustrated and stuck. I found out the hard way which parts of the New Thing I really understood, and which parts I didn’t. I found out the hard way how I can have little moments of tension with others in my group, and I always felt like I could have dealt with it a bit better. I found out that doing projects is a great way to get a sense of what your weaknesses are, as a programmer and as a person. This is stuff that labs and lectures just can’t give you. And though it’s difficult to deal with, the personal growth potential is one of the things that makes it worth it.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=794aa6d9128" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Cross-Origin Resource Sharing (CORS): My Journey]]></title>
            <link>https://medium.com/@jeremylenz/cross-origin-resource-sharing-cors-my-journey-996220c703d8?source=rss-80b960c985f------2</link>
            <guid isPermaLink="false">https://medium.com/p/996220c703d8</guid>
            <category><![CDATA[ajax]]></category>
            <category><![CDATA[mta]]></category>
            <category><![CDATA[cors]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Jeremy Lenz]]></dc:creator>
            <pubDate>Fri, 18 Aug 2017 18:08:24 GMT</pubDate>
            <atom:updated>2017-08-18T18:22:31.519Z</atom:updated>
            <content:encoded><![CDATA[<p>So I was playing around recently with the MTA Bus API. It’s pretty cool. You can get a list of all the bus lines, bus stops, etc.. and even real-time locations of all the vehicles! In Safari, it was working great. I was able to pull down a ton of JSON data from the MTA’s APIs and create JavaScript objects for each one, like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EvIbcai3J25MJjdfWUXnww.png" /></figure><p>But in Chrome, it wasn’t working at all. I would get errors like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*6hLeD_0cwGnGoP3wOJ2-4A.png" /></figure><p>What the heck is an <em>‘Access-Control-Allow-Origin’</em> header? And why do I need one? And why isn’t it there? And if I really need one, why does it work on Safari!?</p><p>(That last one I still haven’t answered. But anyway.)</p><p>I wanted to find out how to resolve this. After consulting with my instructors at Flatiron School and plenty of googling, I discovered lots of different resources online trying to help people resolve this problem. But I noticed something strange. Pretty much all of the posted solutions assumed that you were the <em>owner</em> of the API; that you controlled the server and could make changes to it. See, all you have to do is send back an ‘Access-Control-Allow-Origin’ header of ‘<strong>*</strong>’ and it will work great!</p><p>But alas, I am not the New York Metropolitan Transportation Authority, nor do I control their servers. So what’s going on?</p><p>Turns out that CORS is a standard <strong>enforced by the browser</strong>, and it doesn’t allow cross-origin requests unless the ‘Access-Control-Allow-Origin’ header says so. So what’s the difference between a <strong>cross-origin</strong> request and a <strong>same-origin</strong> request?</p><p>Let’s look at this example:</p><p>Server sending the request: bustime.mta.info<br>Server receiving the request: bustime.mta.info</p><p>The above would be considered a <strong>same-origin request.</strong></p><p>Server sending the request: <a href="http://www.mywebsite.com">www.mywebsite.com</a><br>Server receiving the request: bustime.mta.info</p><p>This would be considered a <strong>cross-origin request.</strong></p><p>So, let’s say the MTA has its own <em>internal</em> web app at bustime.mta.info. That web app can send same-origin requests to its backend API all day, and CORS won’t even be involved. This setup is normally used for API’s that are for internal use only — in other words, not public.</p><p>If the MTA has another web app that’s at a different URL (not bustime.mta.info), they can set their ‘Access-Control-Allow-Origin’ header to allow requests from that specific URL. They know where the request will be coming from, since it’s their own app, so it’s just a matter of configuring their API to allow that request.</p><p>But, you might say, that’s fine for an API that doesn’t send out data to outside developers. But this is supposed to be a <em>public</em> API. Why block cross-origin requests on a public API!?</p><p>I was wondering that too, for the longest time. And then I found <a href="https://groups.google.com/forum/#!searchin/mtadeveloperresources/CORS%7Csort:relevance/mtadeveloperresources/wuCtUcd23tc/7RVtgFV05kwJ"><strong>this</strong></a> post in the MTA Developer BusTime Google Group. It says</p><blockquote>“The MTA’s data feeds are provided without charge to developers who agree to the following:</blockquote><blockquote>1. In developing your app, you will provide that the MTA data feed is available to others <strong>only from a non-MTA server</strong>. Accordingly, you will download and store the MTA data feed on a non-MTA server which users of your App will access in order to obtain data. MTA prohibits the development of an app that would make the data available to others directly from MTA’s server(s).”</blockquote><p>It goes on to suggest that instead, you must provide <strong>your own back-end server</strong> to make the requests and download the MTA feed, and then pass that data on via your own API feed. Since it’s not a browser making the request, CORS will not be an issue.</p><p>So alas, it appears I won’t be getting around this issue any time soon. I guess it’s time for rails new — api.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=996220c703d8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Pair programming: A few observations.]]></title>
            <link>https://medium.com/@jeremylenz/pair-programming-a-few-observations-d17c02628d6b?source=rss-80b960c985f------2</link>
            <guid isPermaLink="false">https://medium.com/p/d17c02628d6b</guid>
            <category><![CDATA[pair-programming]]></category>
            <category><![CDATA[codingbootcamp]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[flatiron-school]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Jeremy Lenz]]></dc:creator>
            <pubDate>Fri, 28 Jul 2017 01:23:41 GMT</pubDate>
            <atom:updated>2017-07-28T01:23:41.311Z</atom:updated>
            <content:encoded><![CDATA[<p>As I write this, we’re at the midpoint of our time at Flatiron School. Seven and a half weeks complete, seven and a half weeks to go. Hard to believe we’ve come this far!</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F133RJTBIIemR8c%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F133RJTBIIemR8c%2Fsource.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F133RJTBIIemR8c%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/0a30938b0675742f6d516810173e0e3d/href">https://medium.com/media/0a30938b0675742f6d516810173e0e3d/href</a></iframe><p>Over the course of my several weeks here, I’ve had the opportunity to do pair programming (also programming in groups of three) quite a bit. People seem to have plenty of opinions about it. I didn’t think I was going to like it at first, but after trying it out I’m pretty much sold.</p><p>In case you’re unfamiliar, the basic idea of pair programming is this: One laptop, two people. The person doing the typing is called the ‘driver.’ The person watching is a kind of supervisor or ‘director.’ The ‘director’ thinks mostly about the ‘big picture,’ telling the driver what to do. The driver actually writes the code and thinks more about the small details such as syntax, etc. Ideally, you switch roles after a while so that everyone spends equal time in the driver’s seat.</p><p>So, after several weeks of this, I thought I would offer some observations, based only on my experience so far at Flatiron. What does pair programming do?</p><h4><strong><em>1. It gives you super powers.</em></strong></h4><p>In my experience, pair programming is GREAT for catching the little things. When there are two pairs of eyes on the code instead of one, stuff like typos and syntax errors are caught almost instantly. Even more often, you prevent the error from being made in the first place. Every time this happens, you may be saving yourself several minutes to an hour of debugging later. If you think of it that way, pair programming saves a ton of time!</p><p><em>Super power #2:</em> You think of solutions you never would have thought of otherwise. You may have a habit of doing something one particular way, while your partner may have a completely different habit. You may realize that your partner’s habit is way more elegant and appropriate than yours, and end up with something new to add to your own bag of tricks. (Als0, you may learn a new keyboard shortcut!! Keyboard shortcuts are the best.)</p><p><em>Super power #3:</em> When it’s 4:32 pm and you’re mentally exhausted and distracted and you can’t think, pair programming can be a lifesaver. Your insurmountable problem may be a simple solution for your partner, who just solved a similar problem the other day. Also, mental tiredness can slow you down quite a bit, and having a partner will make things that much easier.</p><h4>2. To learn the most, work with people just a little better than you.</h4><p>From my previous years of experience playing jazz piano, I had the opportunity to play in lots of different music groups with different people, and this is something I noticed. If you perceive that your group-mates are WAY better than you, you may feel like a burden, or feel overwhelmed. (Not that you should.) Conversely, if you perceive that your partners are much LESS experienced than you, you may feel a bit bored, or even annoyed. And then there’s the ‘Goldilocks’ of ability levels, when you are all very close in ability but you feel like your partners are just a <em>little</em> better than you. If you’re lucky enough to have that experience, it feels like you’re just barely hanging on, but you ARE hanging on. And learning a <em>ton</em>.<br>Even better, if your ability levels are ‘Goldilocks-matched’ and you have a great, respectful relationship with your partners, you may even come across a sort of M.C. Escher-style “cycle of respect” where EACH member of the group feels the same about the others!</p><p>This is barely even an analogy. I think it’s safe to say that all of the above can apply directly to pair programming in addition to music.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F12F18Mg8WYSEiQ%2Ftwitter%2Fiframe&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F12F18Mg8WYSEiQ%2Fgiphy.gif&amp;image=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F12F18Mg8WYSEiQ%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="325" frameborder="0" scrolling="no"><a href="https://medium.com/media/5941818dfaea1fd845adb1dd2f111bcc/href">https://medium.com/media/5941818dfaea1fd845adb1dd2f111bcc/href</a></iframe><h4>3. It gives you an opportunity to get better at SOMETHING, no matter where you are on the ability spectrum.</h4><p>If you’re the less experienced partner, you will get better by driving. That goes without saying. But what if you’re the more experienced person? What if you know all the required concepts and could easily finish coding this by yourself? You STILL have plenty you can learn by teaching your partner, and making sure they understand. Even if you don’t think you have any gaps in understanding, teaching someone is a great way to find out for sure! It can also be an exercise in patience, speaking clearly, and grokking where the other person’s understanding gaps are. All of these are great skills to learn, even if you already know all the code!</p><p>So either way, you’re going to get better — at doing, teaching, or both.</p><p>Oh, and be nice! Everything works better when people are nice.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d17c02628d6b" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>