<?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 Derek Dyer on Medium]]></title>
        <description><![CDATA[Stories by Derek Dyer on Medium]]></description>
        <link>https://medium.com/@derek_dyer?source=rss-3c7156b3039b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*ecmTox4U5vpfmO4h-VYxHg.jpeg</url>
            <title>Stories by Derek Dyer on Medium</title>
            <link>https://medium.com/@derek_dyer?source=rss-3c7156b3039b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 17 Nov 2026 07:35:34 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@derek_dyer/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[AWS | Elastic Beanstalk CLI Setup Mac OS]]></title>
            <link>https://medium.com/@derek_dyer/aws-elastic-beanstalk-cli-setup-mac-os-53b1eafb0b7b?source=rss-3c7156b3039b------2</link>
            <guid isPermaLink="false">https://medium.com/p/53b1eafb0b7b</guid>
            <category><![CDATA[aws]]></category>
            <category><![CDATA[command-line]]></category>
            <category><![CDATA[elastic-beanstalk]]></category>
            <category><![CDATA[terminal]]></category>
            <dc:creator><![CDATA[Derek Dyer]]></dc:creator>
            <pubDate>Wed, 10 Oct 2018 03:00:52 GMT</pubDate>
            <atom:updated>2019-01-30T18:56:48.650Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*H9SN7jwqAcNdNmd2QD0sww.jpeg" /><figcaption>-bash: eb: command not found</figcaption></figure><h3>TL;DR</h3><p><em>(Please let me know if you had trouble with the tl;dr. I had to try a bunch of things to get the Elastic Beanstalk CLI working and I went off a bit of memory and browser history putting this guide together.</em></p><h4>In terminal…</h4><ul><li>You should have python already, ensure this by entering the command:<br>python --version<br>You should see something like this: Python 2.7.10</li><li>Let’s see if you have ‘pip’ installed:<br>Just type pip into terminal if you get:<br>-bash pip: command not found you don’t have pip installed. No worries, we expected that. Try this<br>curl https://bootstrap.pypa.io/get-pip.py | python</li><li>If you get a permissions issue, saying something like this:</li></ul><blockquote>Could not install packages due to an EnvironmentError: [Errno 13] Permission denied: ‘/usr/lib/python2.7/…<br>Consider using the --user option or check the permissions.</blockquote><p>No worries, do this: sudo chown -R $USER/Library/Python/2.7</p><ul><li>Try this again: curl https://bootstrap.pypa.io/get-pip.py | python</li><li>Check to see what versions of Python you have installed do this by running this command in Terminal: ls ~/Library/Python you should get something like this back: 2.7 3.7. Maybe copy the version number of the one that begins with ‘2’. 🆒</li><li>Add Python to your PATH . Remember the Python version we talked about above you’ll need that. User your preferred text editor to open your .bash_profile, ex: atom .bash_profile. Add this to your bash profile: export PATH=&quot;~/Library/Python/your_python_version/bin:$PATH&quot;</li><li>Ok, we should be ready to install the CLI.<br>pip install awsebcli --upgrade --user</li><li>You should have successfully installed 😃. You can verify by entering:<br>eb --version</li></ul><p>You should get something like this back: EB CLI 3.14.6 (Python 2.7.1)</p><p>Praise be 🙏</p><h3>Explanation (You should probably read some of this)</h3><p>I struggled with getting the Elastic Beanstalk CLI setup and it was frustrating because it seems like it should be really easy. In the end it was but I went on a wild goose chase due to what IMO, were not the greatest docs and by that I mean I followed the docs and I did not successfully get the CLI installed. So I thought maybe a blog post would help someone out in the future.</p><h4>PIP VS Homebrew</h4><p>When I started working on getting the AWS EBCLI setup, I found these docs:</p><ul><li><a href="https://aws.amazon.com/getting-started/tutorials/set-up-command-line-elastic-beanstalk/">https://aws.amazon.com/getting-started/tutorials/set-up-command-line-elastic-beanstalk/</a></li><li><a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3-install.html">https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3-install.html</a></li><li><a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3-install-osx.html">https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3-install-osx.html</a> *</li><li>and a bunch of other links when things didn’t work out…</li></ul><p><a href="https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/eb-cli3-install-osx.html">This link</a> * in particular caught my attention. When I saw the brew option as a ruby developer, I was stoked… Home free! Not the case 🤦 . When <em>I</em> tried the brew option, I kept getting a -bash eb: command not found . I’m fairly certain the issue was a python 2 vs Python 3 thing 🤔. I have a version of both and maybe when I ran brew install awsebcli it was installed for 3 but I was ‘using’ 2? Maybe I didn’t have my path right with the brew options? Not sure. But when I explicitly installed pip and set my PATH to target version 2, that was the ticket.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=53b1eafb0b7b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Progressive Web Applications | Push Notifications]]></title>
            <link>https://medium.com/@derek_dyer/progressive-web-applications-push-notifications-d7cfb42f30c3?source=rss-3c7156b3039b------2</link>
            <guid isPermaLink="false">https://medium.com/p/d7cfb42f30c3</guid>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[push-notification]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[progressive-web-app]]></category>
            <dc:creator><![CDATA[Derek Dyer]]></dc:creator>
            <pubDate>Wed, 25 Apr 2018 22:26:01 GMT</pubDate>
            <atom:updated>2018-04-26T03:43:13.211Z</atom:updated>
            <content:encoded><![CDATA[<h4>TL;DR</h4><p><strong>Links to my Proof of Concept:</strong></p><ul><li>Page that has Push notification CTA: <a href="https://digitaldrk.github.io/test_push_notifications/">https://digitaldrk.github.io/test_push_notifications/</a></li><li>Repo for page: <a href="https://github.com/digitaldrk/test_push_notifications">https://github.com/digitaldrk/test_push_notifications</a></li><li>App/API: <a href="https://arcane-stream-87798.herokuapp.com/">https://arcane-stream-87798.herokuapp.com/</a></li><li>Repo for App/API: <a href="https://github.com/digitaldrk/push_notifications">https://github.com/digitaldrk/push_notifications</a></li></ul><p><strong>ALSO</strong>, I hit a nasty bug in chrome that held me up for a while. <a href="https://stackoverflow.com/a/46789047">Here is a link</a> to how to resolve it.</p><p>Link to resources I used:</p><ul><li><a href="https://developers.google.com/web/fundamentals/codelabs/push-notifications/">Adding Push Notifications to a Web App | Web Fundamentals | Google Developers</a></li><li><a href="https://developers.google.com/web/ilt/pwa/introduction-to-push-notifications">Introduction to Push Notifications | Web | Google Developers</a></li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*OTn2OwNg0IYvsLd14Zjuqw.png" /></figure><p>A while ago, I had a conversation about the need for web applications vs. native applications with my good friend and colleague Zack. The consensus we arrived at was if you wanted to send messages to the user, you would need a native app. — a simple but profound realization. Web apps were more about GET-ing information where native apps were able to <em>send</em> messages to the user more or less unsolicited.</p><p>Recently, I’ve been reading about Progressive Web Applications or “PWA’s” and push notifications considered one of the features of PWAs. <a href="https://en.wikipedia.org/wiki/Progressive_Web_Apps#Characteristics">Wikipedia</a> provides these characteristics for PWA’s:</p><blockquote><strong>Progressive</strong> — Work for every user, regardless of browser choice because they’re built with <a href="https://en.wikipedia.org/wiki/Progressive_enhancement">progressive enhancement</a> as a core tenet.</blockquote><blockquote><strong>Responsive</strong> — Fit any form factor: desktop, mobile, tablet, or forms yet to emerge.</blockquote><blockquote><strong>Connectivity independent</strong> — <a href="https://en.wikipedia.org/wiki/Progressive_Web_Apps#Service_Workers">Service workers</a> allow work offline, or on low quality networks.</blockquote><blockquote><strong>App-like</strong> — Feel like an app to the user with app-style interactions and navigation.</blockquote><blockquote><strong>Fresh</strong> — Always up-to-date thanks to the service worker update process.</blockquote><blockquote><strong>Safe</strong> — Served via HTTPS to prevent snooping and ensure content hasn’t been tampered with.</blockquote><blockquote><strong>Discoverable</strong> — Are identifiable as “applications” thanks to W3C manifests<a href="https://en.wikipedia.org/wiki/Progressive_Web_Apps#cite_note-w3cmanifest-6">[6]</a> and service worker registration scope allowing search engines to find them.</blockquote><blockquote><strong>Re-engageable</strong> — Make re-engagement easy through features like <a href="https://en.wikipedia.org/wiki/Push_technology">push notifications</a>.</blockquote><blockquote><strong>Installable</strong> — Allow users to “keep” apps they find most useful on their home screen without the hassle of an app store.</blockquote><blockquote><strong>Linkable</strong> — Easily shared via a URL and do not require complex installation.</blockquote><h3>Push Notifications, what are they?</h3><p>Last weekend, I learned how to implement “push notifications”. Push notifications are the messages you get from websites if you clicked ‘allow’ when prompted. Upon clicking ‘allow’ you allow the site owners to send you notifications like the ones you get from you calendar or other native apps. Push notifications are bad ass because they’re <a href="https://caniuse.com/#search=push">pretty well supported</a> and there is no framework or compiling involved to get this win… thank goodness, we got a break this time 🙏.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*Js9e-HXbKUR-aMG-EJUJfQ.png" /><figcaption>Example of a webpage requesting permission to send push notifications</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/736/1*aRCYqHDjiRcii4MeZp7nZA.png" /><figcaption>Example of notification sent by a site</figcaption></figure><h3>Push Notification Vocabulary</h3><p>In order to create a push notification you need to understand some vocabulary:</p><ul><li><strong>Service Workers</strong>: A <a href="https://developers.google.com/web/fundamentals/primers/service-workers/#what_is_a_service_worker">service worker</a> is a JS file the developer writes that gets installed on the user’s computer. In this case, the service worker has an EventListener that fires when there is a &#39;push&#39; event which is the push notification getting sent to the users browser</li><li><strong>VAPID</strong>: <a href="https://datatracker.ietf.org/doc/rfc8292/">VAPID</a> or ‘The Voluntary Application Server Identification for Web Push” is a JSON Web Token with some extra information that is used to identify your app as the sender of the messages</li><li><strong>VAPID Public and Private Keys</strong>: You will need to generate public and private keys to fulfill push message requirements. There are libraries for just about all languages from what I’ve observed, I used <a href="https://github.com/zaru/webpush">this one</a>. The Public and Private keys are generated using <a href="https://en.wikipedia.org/wiki/Elliptic-curve_Diffie%E2%80%93Hellman">this protocol</a>.</li></ul><h3>Workflow of a Typical Push Notification</h3><ol><li>Check to see if push notifications are supported on the user’s browser</li><li>Register your service worker</li><li>Request permission to send messages</li><li>Generate a PushSubscription object</li><li>Send that PushSubscription object to your application and store it in your DB</li><li>Loop through your subscription records and blast out push notifications</li><li>…</li><li>Profit</li></ol><h4>Check to see if push notifications are supported</h4><p>What’s the point of runin’ a bunch of unsupported code right? Some browsers don’t support push notifications and it’s the usual suspects notably: IE, Edge, and Safari.</p><pre>if (&#39;serviceWorker&#39; in navigator &amp;&amp; &#39;PushManager&#39; in window) {<br>  console.log(&#39;Service Worker and Push is supported&#39;);<br>  // Code that registers service worker...<br>}</pre><p>Not to bad right? Let’s move on…</p><h4>Register Your Service Worker</h4><p>Assuming you have a Service worker we’ll need to register it. <a href="https://github.com/digitaldrk/test_push_notifications/blob/master/service-worker.js">Here’s a link</a> to a service worker I made for a proof of concept to see how push notifications work.</p><pre>if (&#39;serviceWorker&#39; in navigator &amp;&amp; &#39;PushManager&#39; in window) {        <br>  console.log(&#39;Service Worker and Push is supported&#39;);<br>  <br>  navigator.serviceWorker.register(&#39;service-worker.js&#39;)         <br>    .then(function(swReg) {<br>      console.log(&#39;Service Worker is registered&#39;, swReg);           <br>        if (Notification.permission == &#39;default&#39;) {            <br>          // Here we will ask for permission to send notifications<br>        }<br>      swRegistration = swReg;<br>    })<br>      .catch(function(error) {<br>        console.error(&#39;Service Worker Error&#39;, error);<br>      });<br>} else {<br>  console.warn(&#39;Push messaging is not supported&#39;);       <br>  pushButton.textContent = &#39;Push Not Supported&#39;;<br>}</pre><h4>Request permission to send messages</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*Js9e-HXbKUR-aMG-EJUJfQ.png" /><figcaption>Example of a webpage requesting permission to send push notifications</figcaption></figure><p>Let’s pretend this code was ran in a client that does support Push and Service workers. We now ask permission with the askPermission() function which is a nested promise that returns a result of the button click. Permission request status could be ‘default’, ‘granted’, or ‘denied’. This is nice because we can add logic that will not request permission again if the person blocked. This is why I added the conditional checking for Notification.permission == ‘default’</p><pre>if (&#39;serviceWorker&#39; in navigator &amp;&amp; &#39;PushManager&#39; in window) {        <br>  console.log(&#39;Service Worker and Push is supported&#39;);<br>  <br>  navigator.serviceWorker.register(&#39;service-worker.js&#39;)         <br>    .then(function(swReg) {<br>      console.log(&#39;Service Worker is registered&#39;, swReg);           <br>        if (Notification.permission == &#39;default&#39;) {            <br>          askPermission()<br>        }<br>      swRegistration = swReg;<br>    })<br>      .catch(function(error) {<br>        console.error(&#39;Service Worker Error&#39;, error);<br>      });<br>} else {<br>  console.warn(&#39;Push messaging is not supported&#39;);       <br>  pushButton.textContent = &#39;Push Not Supported&#39;;<br>}</pre><pre>...</pre><pre>function askPermission() {<br>  return new Promise(function(resolve, reject) {<br>  const permissionResult = Notification.requestPermission(function(result) {        <br>    resolve(result);<br>    if (result === &#39;granted&#39;) {<br>      // subscribe the user<br>    }<br>  });</pre><pre>  if (permissionResult) {<br>    permissionResult.then(resolve, reject);<br>  }<br>  }).then(function(permissionResult) {<br>    if (permissionResult !== &#39;granted&#39;) {<br>    throw new Error(&#39;We weren\&#39;t granted permission.&#39;);<br>  }<br>});}</pre><h4>Generate a PushSubscription object</h4><p>The first function below askPermission() is the same one from above except we replaced the //subscribe the user comment with the subscribeUser(); function.</p><p>subscribeUser()<br>This function first generates a serverApplication key with the urlBase64ToUint8Array() function which takes our public VAPID key and transforms it into the format that is required by pushManager.subscribe(options). More about pushManager.subscribe(options) after the code snippet below.</p><pre>...</pre><pre>function askPermission() {<br>  return new Promise(function(resolve, reject) {<br>  const permissionResult = Notification.requestPermission(function(result) {        <br>    resolve(result);<br>    if (result === &#39;granted&#39;) {<br>      subscribeUser();<br>    }<br>  });</pre><pre>if (permissionResult) {<br>    permissionResult.then(resolve, reject);<br>  }<br>  }).then(function(permissionResult) {<br>    if (permissionResult !== &#39;granted&#39;) {<br>    throw new Error(&#39;We weren\&#39;t granted permission.&#39;);<br>  }<br>});}</pre><pre>function subscribeUser() {<br>  const applicationServerKey = urlBase64ToUint8Array(&#39;BHdr03Mr4ZU7A2C0kfLCtFQ_Dsl3vFVZL251jtAwVJC_bwKm9p8XIPD38x0BR7mgKjVACAhuCi6LTWWa1gMfOqM=&#39;);<br>  const options = { userVisibleOnly: true,<br>                    applicationServerKey: applicationServerKey<br>  }<br>  return swRegistration.pushManager.subscribe(options)<br>    .then(function(subscription) {     <br>      sendSubscriptionToBackEnd(subscription)<br>    }).catch(function(err) {<br>      console.log(&#39;Failed to subscribe the user: &#39;, err);<br>  });<br>}</pre><pre>...</pre><pre>function urlBase64ToUint8Array(base64String) {<br>  const padding = &#39;=&#39;.repeat((4 - base64String.length % 4) % 4);  <br>  const base64 = (base64String + padding).replace(/<strong>\-</strong>/g, &#39;+&#39;).replace(/_/g, &#39;/&#39;);<br>  const rawData = window.atob(base64);<br>  const outputArray = new Uint8Array(rawData.length);<br>  <br>  for (let i = 0; i &lt; rawData.length; ++i) {<br>    outputArray[i] = rawData.charCodeAt(i);<br>  }<br><br>  return outputArray;<br>}</pre><p>pushManager.Subscribe(options) cont’d:<br>pushManager.subscribe(options) returns a <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise">Promise</a> that resolves to a <a href="https://developer.mozilla.org/en-US/docs/Web/API/PushSubscription">PushSubscription</a> object. This object is our actual user subscription.</p><p>It looks like this:</p><pre>{<br> “endpoint”:”<a href="https://fcm.googleapis.com/fcm/send/fwGhsNG77aY:APA91bG2wM2QRQZ99iQ8AEUeLPlq0R7YVF4SbJxVlAgvm5N5RF3FWMZa9d7Bwme4Z-afIZP6YCVKDgZ7-G3Tqi4-nt4xVyjmz9n2AZGVJZGxzel3eCu7Bku03awi18kEGQm1Zlia6kIv">https://fcm.googleapis.com/fcm/send/fwGhsNG77aY:APA91bG2wM2QRQZ99iQ8AEUeLPlq0R7YVF4SbJxVlAgvm5N5RF3FWMZa9d7Bwme4Z-afIZP6YCVKDgZ7-G3Tqi4-nt4xVyjmz9n2AZGVJZGxzel3eCu7Bku03awi18kEGQm1Zlia6kIv</a>&quot;,<br>  &quot;expirationTime&quot;:null,<br>  &quot;keys&quot;:{<br>    &quot;p256dh&quot;:&quot;BDg5vWXJORoB9-g6OJSz4B8-r09J0vnwZ2ongur6wh-sh2rfZCv6wMSZbYQ_DZJuoSb1MzyV9dIPo_apiU6NzlE=&quot;,<br>    &quot;auth&quot;:&quot;z5W-j90gaGn1Qp1dIQMSbg==&quot;<br>  }<br>}</pre><h4>Send that PushSubscription object to your application and store it in your DB</h4><p>The subscription object we discussed is what we send to our api to persist. I made an <a href="https://github.com/digitaldrk/push_notifications/blob/5c96f655847fe75faf4955d4c0502ea129973e69/app/controllers/subscriptions_controller.rb#L4">api endpoint</a> that takes in the subscription object and parses it and adds it to a Subscriptions table.</p><h4>Loop through your Subscription records and blast out push notifications</h4><p>In my rails app, I have <a href="https://github.com/digitaldrk/push_notifications/blob/5c96f655847fe75faf4955d4c0502ea129973e69/app/views/dashboards/index.html.erb#L5">a simple form</a> with a title and a body. When the form posts, it hits <a href="https://github.com/digitaldrk/push_notifications/blob/5c96f655847fe75faf4955d4c0502ea129973e69/app/controllers/notify_users_controller.rb#L2">an endpoint</a> that gets all Subscriptions, loops through them and uses a <a href="https://github.com/zaru/webpush">gem</a> to distribute the message to all subscribers. I’d like to not use a gem next time, we’ll see though.</p><h4>Profit</h4><p>That’s it! Web notifications were really cool to learn, they’re a great way to engage your users and add a little more polish to your app.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d7cfb42f30c3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails | Webhooks | Local Development]]></title>
            <link>https://medium.com/@derek_dyer/rails-webhooks-local-development-7b7c755d85e3?source=rss-3c7156b3039b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b7c755d85e3</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[webhooks]]></category>
            <category><![CDATA[rails]]></category>
            <dc:creator><![CDATA[Derek Dyer]]></dc:creator>
            <pubDate>Thu, 29 Mar 2018 21:34:54 GMT</pubDate>
            <atom:updated>2018-04-05T11:39:40.187Z</atom:updated>
            <content:encoded><![CDATA[<h4>TL;DR</h4><ol><li>Create a POST route in your rails app</li><li>Download and install <a href="https://ngrok.com/">ngrok</a></li><li>If your development server is running on port 3000, run this command in terminal: ./ngrok http 3000</li><li>URL gets created and printed to your terminal screen, looks something like this: https://foobarchoovak.ngrok.io</li><li>Now if you had a link in your app that looked like this: localhost:3000/facebook_messenger, for the ‘outside world’ to see it, it would look like this: <a href="https://foobarchoovak.ngrok.io/facebook_messenger">https://foobarchoovak.ngrok.io/facebook_messenger</a></li></ol><p>Hi there! Recently, I entered a “Hack-a-thon” with some friends. We didn’t win but that’s ok, we learned a lot and it was for a great cause in the Tampa area, a non-profit called <a href="http://www.metromin.org/">Metropolitan Ministries</a>.</p><p><strong>A little context for you:</strong> The problem we had to solve was that their marketing team was getting inundated with Facebook messages from people looking for assistance.</p><p>We thought it would be cool to build an app that brought in the Facebook messages and allowed our users to respond to them from within our app too. This kept volunteers out of Metropolitan Ministries’s facebook accounts but also freed up marketing folks to focus on well, marketing.</p><p>I was the backend developer for this project so while my teammates explored what assets Metropolitan Ministries(MetMin) had that we might be able to leverage and different frontend frameworks, I researched the Facebook developer documentation.</p><h3>Webhooks</h3><p>I had seen the word ‘webhook’ but had not dedicated anytime to find out what they <em>actually</em> were. After reading about them, I found they were <em>exactly</em> what we needed.</p><h4>What are webhooks?</h4><p>In my use case, I was interested in Facebook messages. I wanted to get a message from Facebook anytime one was sent to my Facebook page. The Facebook Messages webhook would POST the messages from their webhook when a new message or reply was made. So, I had to create an endpoint in our app to listen for the POST. Think of webhooks like maybe a radio or tv station. Radio stations are always broadcasting but we only get the radio’s broadcasted information when we ‘tune-in’ to that radio station’s channel. So, our endpoint was ‘tuned-in’ to the Facebook messages webhook. Perhaps this is an example of a Publisher-Subscribe model.</p><h4>How do we get webhooks to work with our app?</h4><p>As I’m sure you’re aware, in rails we have routes. We can open up paths and define the HTTP method for these routes. Webhooks need a url to POST <strong><em>to</em></strong>, an important detail. So, I made a controller called FacebookMessengerController and made a create action which by default, using resources uses the POST method.</p><p>In Facebook, they needed to know what the link to my app was and this was an interesting issue because I am developing locally and Facebook would have no access to my local development environment.</p><p><strong>So to be clear we have 2 basic options:</strong></p><ol><li>Spend time getting an app up on AWS or Heroku and get the Heroku/AWS url for that app into Facebook configs. Then hope we got everything in the code right but if not, we make make changes, deploy, and test. Very time consuming and tedious.</li><li>Figure out how to get a public link connected to my local dev environment, blast code.</li></ol><h4>Developing with webhooks locally</h4><p>One… word for you: <a href="https://ngrok.com/">ngrok</a>, it’s so cool. You can expose your local dev environment to the outside world. It is so easy to set up. So easy in fact that I’m not going to dignify the process with a how-to, just get it installed and setup using the ngrok docs, it’ll take you 3 minutes.</p><p>Once I had ngrok setup, I ran this command: ./ngrok http 3000 the 3000 is the port your local dev is using so if your locald dev environment is using localhost:3000, you would use the above example. ngrok then spits out 2 urls that look something like this:</p><pre>Forwarding                    http://foobarchoovak.ngrok.io -&gt; localhost:3000</pre><pre>Forwarding                    https://foobarchoovak.ngrok.io -&gt; localhost:3000</pre><p>Notice an http <em>and</em> an https option… nice. In my use case, Facebook needed the https link. So I tested my endpoint (http://foobarchoovak.ngrok.io/facebook_messenger) in <a href="https://www.getpostman.com/">Postman</a> and it worked so I added it to the facebook messenger settings in Facebook and sent a message in the messenger, worked like a charm.</p><p>Thanks for readin’!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b7c755d85e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails | React | Webpacker | ActionCable]]></title>
            <link>https://medium.com/@derek_dyer/rails-react-webpacker-actioncable-283c6ac86ddb?source=rss-3c7156b3039b------2</link>
            <guid isPermaLink="false">https://medium.com/p/283c6ac86ddb</guid>
            <category><![CDATA[actioncable]]></category>
            <category><![CDATA[webpacker]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Derek Dyer]]></dc:creator>
            <pubDate>Tue, 27 Feb 2018 13:01:01 GMT</pubDate>
            <atom:updated>2018-03-25T21:34:46.132Z</atom:updated>
            <content:encoded><![CDATA[<p>I’ve been working on a project that requires websockets. As I’m sure you’re aware, Rails supports websocketing via ActionCable. However, I found that many example apps and how-to’s made use of jQuery, CoffeeScript, and other tools that weren’t applicable to my project. My app uses Webpacker, React, and regular Javascript. Websockets are so cool to me especially paired with React. Hopefully my fumbling through the process of getting my app running with ActionCable will save you some time. It ended up being much easier than I thought.</p><h3>TL;DR (still pretty long)</h3><p>Here’s part of my project’s gemfile FYI</p><pre>gem &#39;pg&#39;, &#39;~&gt; 0.18&#39;<br>gem &#39;puma&#39;, &#39;~&gt; 3.7&#39;<br>gem &#39;rails&#39;, &#39;~&gt; 5.1.4&#39;<br>gem &#39;redis&#39;, &#39;~&gt; 3.0&#39;<br>gem &#39;webpacker&#39;, &#39;~&gt; 3.0&#39;</pre><p>I’ll assume you’ve already installed Rails, created an app, and have some models setup. The below is based on a one to many relationship. <em>Thread</em> has_many <em>Comments.</em></p><ol><li>Uncomment the redis gem in your gemfile and bundle install</li><li>Add mount ActionCable.server =&gt; &#39;/cable&#39; to your routes file</li><li>In app/assets/javascripts/cable.js add this:</li></ol><pre>// Action Cable provides the framework to deal with WebSockets in Rails.<br>// You can generate new channels where WebSocket features live using the `rails generate channel` command.<br>//<br>//= require action_cable<br>//= require_self<br>//= require_tree ./channels</pre><pre>(function() {<br>  this.App || (this.App = {});</pre><pre>App.cable = ActionCable.createConsumer();</pre><pre>}).call(this);</pre><p>4. In config/environments/development.rb add this line: config.action_cable.url = &#39;ws://localhost:3000/cable</p><p>5. In app/views/layouts/application.html.erb add this:<br> &lt;%= action_cable_meta_tag %&gt;</p><p>6. Create a channel, this is where you’re data will be coming <em>from</em> or ‘streaming’. To create a channel add a .rb file with a ‘channel’ suffix to the app/channels folder. Something like this comments_channel.rb:</p><pre>class CommentsChannel &lt; ApplicationCable::Channel<br>  def subscribed<br>    stream_from &quot;comments#{params[:thread]}&quot;<br>  end<br>end</pre><p>7. Add the ‘broadcaster’ to the appropriate controller action (<strong>note:</strong> I made a private method because Rubocop yelled at me for “method has too many lines”). It reads nicer too:</p><pre>def create<br>    <a href="http://twitter.com/idea">@c</a>omment = Comment.new(comment_params)</pre><pre>if <a href="http://twitter.com/idea">@c</a>omment.save<br>      comment_cable(<a href="http://twitter.com/idea">@c</a>omment)<br>      render json: {<br>        success: true, object: <a href="http://twitter.com/idea">@c</a>omment, response_status: success_response<br>      }<br>    else<br>      render json: { success: false, response_status: error_response }<br>    end<br>  end</pre><pre>  private</pre><pre>  def comment_cable(comment)<br>    ActionCable.server.broadcast(<br>      &quot;comments#{comment.thread_id}&quot;,<br>      content: comment.content,<br>      id: comment.id,<br>      votes: comment.votes,<br>      thread_id: comment.thread_id<br>    )<br>  end</pre><p>8. I assume you have a component made, hopefully with state working 🙏. Add this <em>right</em> below your render statement:</p><pre>render() {<br>  const propState = this<br>  App.comments = App.cable.subscriptions.create({<br>    channel: ‘CommentsChannel’,<br>    discussion: `${this.props.threadId}`<br>  }, {<br>    received: function(data) {<br>    propState.updateCommentState(data)<br>  }<br>});<br>...</pre><p>Ok, that’s it, you should be good to go but with all that done, you should probably restart your server. On to the details of the above ☝️.</p><h3>What Did I Want to Accomplish?</h3><ol><li>Create new records and update state with websockets (no updating DOM nodes)</li><li>Scope records to their parent ‘thread’ (like a chatroom)</li><li>Update existing records and update their state</li></ol><p>4. Mitigate use of libraries and dependencies</p><h3>1. Create new records and update state with websockets (no updating DOM nodes)</h3><p>As Ruby/Rails devs, we know how to create records in Controllers and we can leverage this to ensure that ActionCable’s broadcast will only fire if the record was indeed created by placing the broadcast method within the save conditional see the comment_cable(@comment) under the save?:</p><pre>def create<br>    <a href="http://twitter.com/idea">@c</a>omment = Comment.new(comment_params)</pre><pre>if <a href="http://twitter.com/idea">@c</a>omment.save<br>      comment_cable(<a href="http://twitter.com/idea">@c</a>omment)<br>      render json: {<br>        success: true, object: <a href="http://twitter.com/idea">@c</a>omment, response_status: success_response<br>      }<br>    else<br>      render json: { success: false, response_status: error_response }<br>    end<br>  end</pre><pre>private</pre><pre>def comment_cable(comment)<br>    ActionCable.server.broadcast(<br>      &quot;comments#{comment.thread_id]}&quot;,<br>      content: comment.content,<br>      id: comment.id,<br>      votes: comment.votes,<br>      thread_id: comment.thread_id<br>    )<br>  end</pre><p>With our record created and assuming our data is propagating out to ActionCable, we can focus on how we will capture the data sent out by comment_cable(@comment) into State.</p><p>I’ve heard its best practice to not access DOM elements directly with react. ActionCable code examples I found online would use jQuery or vanilla JS and do something like document.getElementById(&#39;comment&#39;) and then append the new record pushed by ActionCable to that div id but that’s not optimal with React.</p><p>I also noticed a lot of examples using the channel directory to create channels that would update the DOM, 🤔 makes sense but I couldn’t think of a way to update a component’s state outside of the component so I just added the subscription directly to the component forgoing the channel directory. Let me know if you have a better solution, I would be interested to see other approaches.</p><pre>render() {<br>    const propState = this<br>    App.comments = App.cable.subscriptions.create({<br>      channel: &#39;CommentsChannel&#39;,<br>      thread: `${this.props.threadId}`<br>    }, {<br>      received: function(data) {<br>        propState.updateCommentState(data)<br>      }<br> });</pre><p>☝️Here, we set a variable propState to this so we can carry that context into the function and access the component’s props. Subscriptions is available to us which is really cool. Also not worthy, I have created an updateCommentState() function that I passed down as a prop(function will be shown shortly). That’s it, we have the subscriptions updating state in a component 👏.</p><h3>2. Scope records to their parent ‘thread’ (like a chatroom)</h3><p>Once I had Comments blasting out of ActionCable, I quickly discovered they were unfortunately blasting to <em>everyone</em> that had <em>any</em> thread (like a chatroom) open. I had to keep comments scoped to their own thread.</p><p>To accomplish this, I used the relationship between Thread and Comment which is Thread has_many :comments Comment belongs_to :thread. I had the comment form push it’s thread id to the controller action so that it was available and passed it like this in the channel app/channels/comments_channel.rb:</p><pre>app/channels/comments_channel.rb<br>class CommentsChannel &lt; ApplicationCable::Channel<br>  def subscribed<br>    stream_from &quot;comments#{params[:thread]}&quot;<br>  end<br>end</pre><p>☝️Notice how there are params like in a controller, pretty cool. Many blogs have referred to Channels as “the controllers of ActionCable”.</p><p>Let’s look at that private method in the controller again real quick so we can see how the data is going from the app/controllers/comments_controller.rb <em>TO</em> the app/channels/comments_channel.rb subscribed method.</p><pre>app/controllers/comments_controller.rb<br>...<br>  private</pre><pre>def comment_cable(comment)<br>    ActionCable.server.broadcast(<br>      &quot;comments#{comment.thread_id}&quot;,<br>      content: comment.content,<br>      id: comment.id,<br>      votes: comment.votes,<br>      thread_id: comment.thread_id<br>    )<br> end</pre><p>☝️See what we’re doing? Passing the comment object we created in the controller action as comment. In the ActionCable.server.broadcast method, First argument is the ‘stream’ with the thread_id which scopes comments to that thread, following arguments will be the params for the channel that we need to send to our component.</p><h3>3. Update existing records and update their state</h3><p>Cool, let’s recap real quick:</p><ol><li>Data is sent via fetch/XMLHttpRequest to the controller action</li><li>Controller action initializes and then hits the save conditional</li><li>If save conditional is true, data goes off to database and ActionCable.server.broadcast fires a broadcast with a Comment object to the comments_channel.rb</li><li>comments_channel.rb has a subscribed method ‘streaming’ comment objects</li><li>React component is subscribed to the comments stream we have in the comments_channel.rb file mentioned above</li></ol><h4>Now state</h4><p><em>You may just want to copy the code below and paste it into your text editor. Code formatting isn’t the best.</em></p><pre>updateCommentState(comment) {<br>    let comments = [...this.state.comments]<br>    let commentCopy = comments.slice()<br>    let commentIndex = commentCopy.findIndex((element, index, array) =&gt; element.id == comment.id)</pre><pre>if (commentIndex == -1) {<br>      commentCopy.push(comment)<br>    } else {<br>      commentCopy[commentIndex] = comment<br>    }</pre><pre>this.setState( {comments: commentCopy} )<br>  }<br><br>  render() {<br>    const propState = this<br>    App.comments = App.cable.subscriptions.create({<br>      channel: &#39;CommentsChannel&#39;,<br>      thread: `${this.props.threadId}`<br>    }, {<br>      received: function(data) {<br>      propState.updateCommentState(data)<br>    }<br>  });</pre><p>The component in render is sent the comment object when it’s created and at the bottom, fires the updateCommentState(data) method. Up in the updateCommentState(data) function, we get initial state, then make a copy of it because it’s bad practice to mutate state. Next we prepare for a fork in the road. 1 of 2 things is happening to a comment, it’s either getting created or it’s being updated with a vote. So, we check to see if the comment is in the array. Next in the conditional, if the commentIndex == -1, we know it’s new and we append it to the end of the array with the push function. If it’s equal to anything else, we update our copy of the state array at the index with our comment object which already has the new number of votes. Finally, we set the state. 👍</p><h3>4. Mitigate use of libraries/dependencies and closing</h3><p>Along the way of learning how to use ActionCable with React and Webpacker, I asked some Slacks I belong to and coworkers for advice. I am super grateful for the colleagues and coworkers I’m surrounded by and there were some great suggestions that helped me get to the win. All advice was good however, there were some suggestions to leverage various gems and node modules. I’m all for getting the work done and out of the way but so far this project has been pretty simple and I didn’t want to too lose sight of what’s happening.</p><p>If I could share any advice it would be to tread carefully with adding libraries. When I decided to dedicate some real time to learn React in particular, I resolved to not use features or libraries until I needed them. I think this has helped me a lot in getting the basics down, troubleshooting, and most importantly, why features and tools exist and what they do because I had a <em>need</em> for them.</p><p>Thanks for reading! 😎</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=283c6ac86ddb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails | React | Webpacker | Forms | Fetch]]></title>
            <link>https://medium.com/@derek_dyer/rails-react-webpacker-forms-fetch-6f1bc755f4f2?source=rss-3c7156b3039b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6f1bc755f4f2</guid>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[webpacker]]></category>
            <category><![CDATA[forms]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Derek Dyer]]></dc:creator>
            <pubDate>Tue, 20 Feb 2018 13:01:01 GMT</pubDate>
            <atom:updated>2018-03-07T21:44:23.671Z</atom:updated>
            <content:encoded><![CDATA[<p>First, I have to give credit to a great post that helped solve a frustrating form problem. <a href="https://medium.com/@everdimension/how-to-handle-forms-with-just-react-ac066c48bd4f">This article</a> with a couple tweaks to my needs, was the key to getting my forms working right and my code lookin’ tight. I don’t know <a href="https://medium.com/@everdimension">everdimension</a> at all but thank you for a great post, you helped me out a lot.</p><h3>TL;DR</h3><ol><li>Use onSubmit in the form not onClick in your submit button</li><li>Don’t use a type with the button, maybe type=&quot;submit&quot; if you must but definitely not type=&quot;button&quot;</li><li>I used a ref in the form so that I could clear the form after submit</li><li>Put this in your application.html.erb template file: <br>const formToken = “&lt;%=form_authenticity_token%&gt; 👈 You’ll need that so Rails will accept your forms.</li></ol><h3>The Problem</h3><p>I had fetch working with my forms with a helper method but there were some issues. If the cursor was in a form field and the user pressed enter/return the browser would seem to make a GET request and the browser would have a query string in it. If there was content in the field, it would do the same but with the content that was in the form field, in the query string. I read a lot of articles but the one mentioned above was what helped me. I was able to take its simple example and fit it to my needs.</p><h3>The Fix</h3><p>Below is my helper method. So far things are going pretty well with it. I like it because it keeps form stuff DRY but not too abstract. We’ll see how it works as things get more complicated in my app.</p><pre>app/javascript/helpers/fetch_form_helper.js:</pre><pre>import &quot;whatwg-fetch&quot;<br>import Promise from &quot;promise-polyfill&quot;;<br>import setAsap from &quot;setasap&quot;;</pre><pre>Promise._immediateFn = setAsap;</pre><pre>function checkStatus(response) {<br>  if (response.status &gt;= 200 &amp;&amp; response.status &lt; 300) {<br>    return response<br>  } else {<br>    var error = new Error(response.statusText)<br>    error.response = response<br>    throw error<br>  }<br>}</pre><pre>export function fetchFormHelper(endPoint, formData, callback, method=&quot;POST&quot;) {<br>  fetch(endPoint, {<br>    method: method,<br>    credentials: &quot;same-origin&quot;,<br>    headers: {<br>      &#39;X-Requested-With&#39;: &#39;XMLHttpRequest&#39;,<br>      &#39;X-CSRF-Token&#39;: formToken<br>    },<br>    body: new FormData(formData)<br>  })<br>  .then(checkStatus)<br>  .then(response =&gt; response.json())<br>  .then((responseObject) =&gt; {<br>    callback(responseObject)<br>  }).catch(function(error) {<br>    console.log(&#39;Bad server response 🍤&#39;, error)<br>  })<br>}</pre><p>☝️I think it’s important to mention that I have a variable equal to the rails form token in my application.html.erb file like this:<br> const formToken = “&lt;%=form_authenticity_token%&gt;. <strong>You’ll need that for rails to accept your forms. </strong>Note the default param passed as the last argument method=&quot;POST&quot;. Most of the time, we’re POSTn’ stuff so I thought that would be a good move 🤔.</p><p>Below is an example of a form I have in my app. All it does is send a Topic object with a title attribute.</p><pre>app/javascript/components/topics_form.js:</pre><pre>import React from &#39;react&#39;<br>import PropTypes from &#39;prop-types&#39;<br>import { fetchFormHelper } from &#39;../../helpers/fetch_form_helper&#39;</pre><pre>class TopicsForm extends React.Component {<br>  constructor() {<br>    super()</pre><pre>    this.handleSubmit = this.handleSubmit.bind(this);<br>    this.updateDom = this.updateDom.bind(this)<br>  }</pre><pre>handleSubmit(event) {<br>    event.preventDefault()<br>    fetchFormHelper(this.props.endPoint, event.target, this.updateDom)<br>}</pre><pre>updateDom(responseObject) {<br>    this.props.updateMessageState(responseObject.response_status)<br>    this.props.updateTopicState(responseObject.object)<br>    this.topicForm.reset()<br>  }</pre><pre>render() {<br>    return(<br>      &lt;form onSubmit={this.handleSubmit} id={this.props.formId} ref={(input) =&gt; this.topicForm = input} className={this.props.className}&gt;<br>        &lt;input<br>          name=&quot;topic[title]&quot;<br>          className=&quot;topics-field&quot;<br>          type=&quot;text&quot;<br>          id=&quot;topics-field-id&quot;<br>          placeholder=&quot;Enter a New Topic&quot;<br>        /&gt;<br>        &lt;button<br>          id=&quot;topic-submit-button&quot;<br>          className=&quot;button-topics-class&quot;<br>        &gt;<br>        Create a Topic<br>        &lt;/button&gt;</pre><pre>&lt;/form&gt;<br>    )<br>  }<br>}</pre><pre>export default TopicsForm</pre><p>The things worth noting are (Pretty much the TL;DR again):</p><ol><li>Use onSubmit in the form not onClick in a button</li><li>Don’t use a type with the button, maybe type=&quot;submit&quot; if you must but definitely not type=&quot;button&quot;</li><li>I used a ref in the form so that I could clear the form after submit</li></ol><p>That’s it! Hope it helped you out, thanks for reading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6f1bc755f4f2" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruby | Rspec | Mocks & Stubs]]></title>
            <link>https://medium.com/@derek_dyer/ruby-rspec-mocks-stubs-7b21ea176b13?source=rss-3c7156b3039b------2</link>
            <guid isPermaLink="false">https://medium.com/p/7b21ea176b13</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[rspec]]></category>
            <category><![CDATA[stub]]></category>
            <category><![CDATA[mock]]></category>
            <dc:creator><![CDATA[Derek Dyer]]></dc:creator>
            <pubDate>Thu, 16 Nov 2017 14:01:02 GMT</pubDate>
            <atom:updated>2017-11-19T23:58:18.756Z</atom:updated>
            <content:encoded><![CDATA[<p>I struggled with the concept of Mock vs. Stub for a little while and it wasn’t until I was in a paired programming session with <a href="https://twitter.com/makagon?lang=en">Sergii Makagon</a> that it finally clicked for me. Seeing the process of adding mocks and stubs evolve during a refactoring session helped me understand the two concepts, so I wanted to try and explain mocks and stubs in a similarly iterative way.</p><h4>Vocabulary:</h4><p><strong>Double:</strong> It’s a dumb object we create that stands-in for an object we <em>need</em> in order to test something.</p><p><strong>Stub:</strong> Stubs <em>allow</em> an object to receive messages/methods. Usually they’re Doubles but we can allow ‘real’ objects to receive messages/methods too.</p><p><strong>Mock:</strong> Objects with <em>expectations.</em> Key word being expect.</p><h4>Why do we need Doubles?</h4><p>Doubles are cool because sometimes classes rely on other objects in order to work. Doubles make it easy to test a class’s methods without having to instantiate objects. In unit testing, we try to be as <em>lazy</em> as possible. We want to instantiate the bare minimum to get a test to pass. We should never care about anything else except <em>that</em> method we’re testing at <em>that</em> time.</p><h4>Why do we need Stubs?</h4><p>Sometimes we rely not only on objects but those objects’ methods/messages too. We can use stubs to mimic those methods/messages.</p><h4>Why do we need Mocks?</h4><p>Sometimes a test expects certain messages from objects. We can add these messages at runtime for that test. We can expect a method response from a mock to fulfill the tested method’s needs.</p><h4>Some quick boilerplate code for context:</h4><p>The code below implements a simple example of dependency injection.</p><p>user.rb:</p><pre>class User<br>  attr_reader :email, :first_name, :last_name, :phone_number<br>  def initialize(email:, first_name:, last_name:, phone_number:)<br>    @email = email<br>    @first_name = first_name<br>    @last_name = last_name<br>    @phone_number = phone_number<br>  end<br>end</pre><p>identity_provider.rb (like a class interface)</p><pre>class IdentityProvider<br>  def self.authenticate(_email)<br>    ‘The self.authenticate method has not been defined for this Identity Provider 🙊’<br>  end<br>end</pre><p>twitter_idp.rb</p><pre>class TwitterIdp &lt; IdentityProvider<br>  def self.authenticate(email)<br>    “Authenitcated 🔓 using #{name.split(‘::’).last} with email: <br>#{email}”<br>  end<br>end</pre><p>salesforce_idp.rb</p><pre>class SalesforceIdp &lt; IdentityProvider<br>  def self.authenticate(email)<br>    “Authenitcated 🔓 using #{name.split(‘::’).last} with email: #{email}”<br>  end<br>end</pre><p>facebook_idp.rb</p><pre>class FacebookIdp &lt; IdentityProvider; end</pre><p>session.rb</p><pre>require_relative &#39;user&#39;<br>require_relative &#39;identity_provider&#39;<br><br>class Session<br>  attr_reader :current_user<br>  def initialize(user)<br>    <a href="http://twitter.com/current_user">@current_user</a> = user<br>  end</pre><pre>  def create(idp = SalesforceIdp)<br>    idp.authenticate(current_user.email)<br>  end<br>end</pre><p>run_idp.rb</p><pre>require_relative ‘session’<br>session = Session.new(<br>  User.new(<br>    email: ‘<a href="/service/mailto:derekdyer2@gmail.com">foobar@gmail.com</a>’,<br>    first_name: ‘Derek’,<br>    last_name: ‘Dyer’,<br>    phone_number: ‘5555555555’<br>  )<br>)</pre><pre>session.create(TwitterIdp)<br>session.create(FacebookIdp)<br>session.create</pre><h4>Double</h4><p>I want to test Session#create, so I made a file called session_spec.rb with an empty test in it.</p><pre>require_relative &#39;session&#39;<br>RSpec.describe Session do</pre><pre>  it &#39;creates a new session&#39; do<br>  end<br>end</pre><p>We set ‘session’ to equal the class we are testing: Session. Looking at the ‘session.rb’ file, Session needs a User object in order for Session to be initialized. Instantiating the User class is totally an option:</p><pre>require_relative &#39;session&#39;<br>RSpec.describe Session do</pre><pre>  let(:current_user) do<br>    User.new(<br>      email: &#39;<a href="/service/mailto:derekdyer2@gmail.com">foobar@gmail.com</a>&#39;,<br>      first_name: &#39;Derek&#39;,<br>      last_name: &#39;Dyer&#39;,<br>      phone_number: &#39;5555555555&#39;<br>    )<br>  end</pre><pre>  let(:session) { described_class.new(current_user) }</pre><pre>  describe &#39;#create&#39; do<br>    it &#39;creates a new session&#39; do<br>    end<br>  end<br>end</pre><p>We’re instantiating the User class for what? To test the Session#create method. Let’s look at what that method needs from User to run:</p><p>In the session.rb file:</p><pre>def create(idp = SalesforceIdp)<br>  idp.authenticate(current_user.email)<br>end</pre><p>It needs an instance of the User class (it also needs an email from User but we’ll get to that later).</p><p>let(current_user) { double(&#39;user&#39;)</p><p>That 👆 is a double using the Rspec double method. I like to think of it as a stunt double. Let’s run it with a simple test.</p><pre>require_relative ‘session’<br>RSpec.describe Session do</pre><pre>  let(:current_user) { double(‘user’) }</pre><pre>  let(:session) { described_class.new(current_user) }</pre><pre>  describe ‘#create’ do<br>    it ‘creates a new session’ do<br>      expect(session.create).to eq(<br>      “Authenticated 🔓 using SalesforceIdp with email: #{current_user.email}”<br>      )<br>  end<br>end</pre><blockquote>#Double “current_user”&gt; received unexpected message :email with (no args)</blockquote><p>Ok, we’re getting somewhere. When we ran the test for Session#create we got the above error. We need the current_user’s email. We have a few options.</p><h4>Stub</h4><p>Definition of stub:</p><blockquote>A method stub is an instruction to an object (real or test double) to return a<br>known value in response to a message.</blockquote><p>That sounds useful. Let’s try it with: allow(current_user).to receive(:email)</p><pre>require_relative &#39;session&#39;<br>RSpec.describe Session do</pre><pre>let(:current_user) { double(&#39;current_user&#39; }</pre><pre>let(:session) { described_class.new(current_user) }</pre><pre>describe &#39;#create&#39; do<br>    it &#39;creates a new session&#39; do<br>      allow(current_user).to receive(:email)</pre><pre>      expect(session.create).to eq(<br>      &quot;Authenitcated 🔓  using SalesforceIdp with email: #{current_user.email}&quot;<br>      )<br>    end<br>  end<br>end</pre><p>It worked! We instructed the user object to respond to email and our test is passing. Also, notice how much cleaner that is than if we instantiated a User object. If we were relying on current_user.email to respond with something specifically, we could have done this:</p><p>allow(current_user).to receive(:email) { &#39;email@email.com&#39; }</p><p>As it turns out, the Session#create method doesn’t really care what current_user.email returned, as long as it responded to the method.</p><p><em>FYI, we can also stub methods for real objects too. Stubs are not just applicable to mocks.</em></p><h4>Mock</h4><p>Remember we said a mock was like a stub but with an <em>expectation</em>? Let’s see what that looks like.</p><pre>require_relative &#39;session&#39;<br>RSpec.describe Session do</pre><pre>let(:current_user) { double(&#39;current_user&#39; }</pre><pre>let(:session) { described_class.new(current_user) }</pre><pre>describe &#39;#create&#39; do<br>    it &#39;creates a new session&#39; do<br>      expect(current_user).to receive(:email) { &#39;<a href="/service/mailto:email@email.com">email@email.com</a>&#39; }</pre><pre>      expect(session.create).to eq(<br>        &quot;Authenticated 🔓  using SalesforceIdp with email: email@email.com&quot;<br>      )<br>    end<br>  end<br>end</pre><p>This is better, it is more specific. It’s verifying that the session.create method is calling the method the way it’s supposed to.</p><h4>Verifying doubles (Bonus Round)</h4><blockquote>Most of the time you will want some confidence that your doubles resemble an existing object in your system. Verifying doubles are provided for this purpose. If the existing object is available, they will prevent you from adding stubs and expectations for methods that do not exist or that have invalid arguments.</blockquote><blockquote><a href="https://relishapp.com/rspec/rspec-mocks/docs/verifying-doubles">Verifying doubles</a> have some clever tricks to enable you to both test in isolation without your dependencies loaded while still being able to validate them against real objects.<br><a href="https://relishapp.com/rspec/rspec-mocks/docs">https://relishapp.com/rspec/rspec-mocks/docs</a></blockquote><p>We have a nice test. Let’s try a verifying double like this:</p><pre>let(current_user) do<br>  instance_double(&#39;User&#39;, email: &#39;email@email.com&#39;)<br>end</pre><p>session_spec.rb</p><pre>require_relative &#39;session&#39;</pre><pre>RSpec.describe Session do</pre><pre>let(:current_user) do<br>  instance_double(&#39;User&#39;, email: &#39;<a href="/service/mailto:foo@foo.com">foo@foo.com</a>&#39;)<br>end</pre><pre>let(:session) { described_class.new(current_user) }</pre><pre>  describe &#39;#create&#39; do<br>    it &#39;creates a new session&#39; do<br>      expect(session.create).to eq(<br>        &quot;Authenitcated 🔓  using SalesforceIdp with email: #{current_user.email}&quot;<br>      )<br>    end<br>end</pre><p>The cool thing about verifying doubles is they prevent us from adding stubs for methods that do not exist in the actual class or that have invalid arguments. So by changing user to User, we are now mocking with confidence because the verifying double is checking to see if an instance method exists <em>AND</em> we’re testing in isolation without instantiating a class <em>AND</em> we’re stubbing.</p><p>Thanks for your time!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=7b21ea176b13" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruby | SimpleDelegator Methods]]></title>
            <link>https://medium.com/@derek_dyer/ruby-simpledelegator-methods-c799e07ae108?source=rss-3c7156b3039b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c799e07ae108</guid>
            <category><![CDATA[decorator-pattern]]></category>
            <category><![CDATA[simpledelegator]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Derek Dyer]]></dc:creator>
            <pubDate>Thu, 09 Nov 2017 16:47:30 GMT</pubDate>
            <atom:updated>2017-11-12T23:06:08.415Z</atom:updated>
            <content:encoded><![CDATA[<p>There are a good number of posts about the OOP ‘decorator’ pattern using SimpleDelegator in ruby, this is another one 😉. More specifically though, this one is about all two instance methods available in the SimpleDelegator class: __getobj__ and __setobj__. I hope after reading this post, you will be a little more comfortable with SimpleDelegator and using its methods.</p><h4>Context</h4><p>I don’t know what made me think of this as an example but 7/11 gives out free slurpees on July, 11th. So we’ll work on a couple files that print out results for free a slurpee day.</p><h4>Basic Decorator Pattern</h4><p>Let’s start simple. You’re probably already familiar with how to implement a decorator but just in case you’re not, check out the code example below:</p><p>The slurpee.rb file with the Slurpee class.</p><pre>require &#39;date&#39;<br>class Slurpee<br>  attr_reader :flavor, :size, :cost<br>  def initialize(flavor, size, cost)<br>    <a href="http://twitter.com/flavor">@flavor</a> = flavor<br>    <a href="http://twitter.com/size">@size</a> = size<br>    <a href="http://twitter.com/cost">@cost</a> = cost<br>  end<br>end</pre><p>the slurpee_day_decorator.rb file with our decorator class.</p><pre>class SlurpeeDayDecorator &lt; SimpleDelegator<br>  def serve<br>    &quot;Serving one #{size} slurpee in a delicious flavor #{flavor}  and it will cost you $#{cost}&quot;<br>  end<br>end</pre><p>To get our desired return out of the decorator we’ll do this:</p><pre>slurpee = Slurpee.new(&#39;🍉&#39;, &#39;massive&#39;, 5.00)<br>slurpee_day = SlurpeeDayDecorator.new(slurpee)</pre><p>We’re instantiating the Slurpee class and then passing the slurpee object into the SlurpeeDayDecorator class as an argument. This is how we implement a decorator using SimpleDelegator.</p><p>Now we can do something like: slurpee_day.serve and it should return “Serving one massive 🍉 slurpee. It will cost you $5.00”</p><p><strong><em>Notice how the Slurpee class’s instance methods, size, flavor, and cost are available within the SlurpeeDayDecorator class.</em></strong></p><p>So that is a simple example of using SimpleDelegator but let’s learn about the __getobj__ and __setobj__ methods.</p><h4>__getobj__</h4><blockquote>Returns the current object method calls are being delegated to.<br><a href="http://ruby-doc.org/stdlib-2.4.1/libdoc/delegate/rdoc/SimpleDelegator.html#method-i-__getobj__">http://ruby-doc.org/stdlib-2.4.1/libdoc/delegate/rdoc/SimpleDelegator.html#method-i-__getobj__</a></blockquote><p>__getobj__ returns the Slurpee object being injected into the SlurpeeDayDecorator. Let’s puts __getobj__ from inside a quick made up instance method in the SlurpeeDayDecorator and see what we get back:</p><p>slurpee_day_decorator.rb</p><pre>...</pre><pre>def foo<br>  puts __getobj__<br>end</pre><pre>...</pre><p>slurpee = Slurpee.new(‘🍉’, ‘massive’, 5.00)<br>slurpee_day = SlurpeeDayDecorator.new(slurpee).foo</p><p>☝️ returns: “#&lt;Slurpee:0x007fff12095dd0&gt;”</p><p>See? Just a regular Slurpee object. Let’s do the same thing but also call a Slurpee instance method.</p><p>slurpee_decorator.rb</p><pre>def foo<br>  puts __getobj__.cost<br>end</pre><p>slurpee = Slurpee.new(‘🍉’, ‘massive’, 5.00)<br>slurpee_day = SlurpeeDayDecorator.new(slurpee)<br>slurpee_day.foo</p><p>👆 returns: 5.0. So with adding the __getobj__ method we’re able to call instance methods in the Slurpee class from the SlurpeeDayDecorator instance. <strong>BUT wait a minute</strong>, what’s the point of __getobj__ if we can <strong><em>already</em></strong> call instance methods in the SlurpeeDayDecorator class? With __getobj__ we can seemingly <em>change</em> but more like overwrite the behavior of our Slurpee instance methods in the <strong><em>context</em></strong> of slurpee day in the SlurpeeDayDecorator class.</p><p>Let’s use the __getobj__ method in the SlurpeeDayDecorator class for real now.</p><p>slurpee_decorator.rb</p><pre>def cost<br>    __getobj__.cost - __getobj__.cost<br>end</pre><p>slurpee = Slurpee.new(‘🍉’, ‘massive’, 5.00)<br>slurpee_day = SlurpeeDayDecorator.new(slurpee)<br>slurpee_day.cost</p><p>👆 returns: 0.0</p><p>Just to recap, we created a cost method in the SlurpeeDayDecorator because we wanted to get the cost in the context of the free slurpee day.</p><p>Let’s add another one to calculate the days until Free Slurpee Day.</p><p>slurpee_day.rb (with a new free_slurpee_day method)</p><pre>class Slurpee<br>  attr_reader :flavor, :size, :cost<br>  def initialize(flavor, size, cost)<br>    <a href="http://twitter.com/flavor">@flavor</a> = flavor<br>    <a href="http://twitter.com/size">@size</a> = size<br>    <a href="http://twitter.com/cost">@cost</a> = cost<br>  end</pre><pre>  def free_slurpee_day<br>    today = Date.today<br>    year = today &lt; Date.new(today.year, 8, 21) ? today.year : today.year + 1<br>    Date.new(year, 8, 21)<br>  end<br>end<br></pre><p>slurpee_decorator.rb</p><pre>def free_slurpee_day<br> number_of_days = __getobj__.free_slurpee_day — Date.today<br> “There are #{number_of_days.to_i} days until Free Slurpee Day”<br>end</pre><p>👆 returns: “There are 245 days until Free Slurpee Day”</p><h4>__setobj__</h4><p>This one is a little more interesting. Using __setobj__ we can change the ‘original’ object decoratin’ in the same instance of the decorator class. I could see a use case for this where if there was a condition, we could change the object based on that condition. We had a Slurpee class, let’s add a… HotDog class.</p><p>hot_dog.rb</p><pre>class HotDog<br>  attr_reader :size, :cost<br>  def initialize(size, cost)<br>    <a href="http://twitter.com/cost">@cost</a> = cost<br>    <a href="http://twitter.com/size">@size</a> = size<br>  end</pre><pre>  def free_day<br>    today = Date.today<br>    year = today &lt; Date.new(today.year, 8, 21) ? today.year : today.year + 1<br>    Date.new(year, 8, 21)<br>  end<br>end</pre><p>Let’s refactor our decorator file since it will be decorating different objects now. We’ll change the file name, class name, method names, and get the name of the class and format it using our friend __getobj__.</p><p>free_decorator.rb (formerly slurpee_day_decorator.rb)</p><pre>class FreeDecorator &lt; SimpleDelegator<br>  def free_day<br>    number_of_days = __getobj__.free_day - Date.today<br>    &quot;There are #{number_of_days.to_i} days until Free #{format_constant} Day&quot;<br>  end</pre><pre>  def serve<br>    &quot;Dispensing one #{size} #{format_constant} in a delicious flavor #{flavor}  and it will cost you $#{cost}&quot;<br>  end</pre><pre>  def cost<br>    __getobj__.cost - __getobj__.cost<br>  end</pre><pre>  private</pre><pre>  def format_constant<br>    __getobj__.class.name.gsub(/(?&lt;=[a-z])(?=[A-Z])/, &#39; &#39;)<br>  end<br>end</pre><p>Ok, let’s use __setobj__ and puts the results to see what we get.</p><p>hot_dog = HotDog.new(‘jalapeno’, ‘footlong’, 5.00)<br>slurpee = Slurpee.new(‘🍉’, ‘massive’, 5.00)<br>free_item = FreeDecorator.new(slurpee)<br>puts free_item.free_day<br>free_item.__setobj__(hot_dog)<br>puts free_item.free_day</p><p>👆 returns:<br>There are 244 days until Free Slurpee Day<br>There are 285 days until Free Hot Dog Day</p><p>Thanks for reading!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c799e07ae108" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails | Webpacker | Yarn | ESLint & Aliases]]></title>
            <link>https://medium.com/@derek_dyer/rails-webpacker-yarn-eslint-aliases-ed18a4669517?source=rss-3c7156b3039b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ed18a4669517</guid>
            <category><![CDATA[eslint]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[yarn]]></category>
            <category><![CDATA[rails-5]]></category>
            <category><![CDATA[webpacker]]></category>
            <dc:creator><![CDATA[Derek Dyer]]></dc:creator>
            <pubDate>Tue, 10 Oct 2017 19:26:01 GMT</pubDate>
            <atom:updated>2017-11-10T21:25:12.335Z</atom:updated>
            <content:encoded><![CDATA[<h3>TL;DR</h3><p>config/webpack/shared.js</p><pre>resolve: {<br>  alias: {<br>    Helpers: resolve(&#39;path/to/helpers_directory&#39;),<br>    Components: resolve(&#39;path/to/components_directory&#39;)<br>  }<br>}</pre><p>.eslintrc.json</p><pre>&quot;settings&quot;: {<br>  &quot;import/resolver&quot;: {<br>    &quot;webpack&quot;: {<br>      &quot;config&quot;: &quot;config/webpack/shared.js&quot;<br>  }<br>}</pre><p>New command to run eslint (we run this in our rakefile):<br>NODE_ENV=development yarn lint</p><h3>The problem</h3><p>Recently at work, I picked up a Kanban that asked for the removal of gnarly relative links in our frontend directories ex:</p><p>import Helper from ../../../helpers/cool_helper.js</p><p>This is sub-optimal for many reasons. What if we decide to move components around? How fun is it to figure out the project structure relative where your file is? Plus it looks gross 🤢.</p><h3>Aliases</h3><p>This is pretty straight forward. After thinking about it, I decided to go with aliases as opposed to modules. I like the idea that I can capitalize the alias and when other developers look at the import statement, they’ll know it’s an alias because it’s… more explicit IMHO.</p><pre>resolve: {<br>  alias: {<br>    Helpers: resolve(&#39;path/to/helpers_directory&#39;),<br>    Components: resolve(&#39;path/to/components_directory&#39;)<br>  }<br>}</pre><p>Now our import statements look like this:</p><p>import Helper from &quot;Helpers/cool_helper.js 👍</p><h3>ESLint</h3><p>This is where things got interesting. There’s tons of documentation on webpack, aliases, and ESLint but not much just yet on webpack<em>er</em>. After getting aliases working, I ran our rake task as part of our SOP for submitting pull requests. To my dismay, ESLint lit up like a Christmas tree.</p><pre>...<br>import/extensions<br>import/no-unresolved<br>...</pre><p>In eslintrc.json, I added this:</p><pre>”settings”: {<br>  “import/resolver”: {<br>  “webpack”: {<br>  “config”: “config/webpack/shared.js”<br>  }<br>}</pre><p>The idea here is that we link to the shared.js folder because it references the development.js for the environment <em>and</em> the configuration.js file.</p><p>After adding that, I got <em>more</em> errors in addition to the above saying this:</p><pre>error Resolve error: Cannot read property ‘public_output_path’ of undefined import/no-named-as-default-member</pre><p>After a <em>lot</em> of googlin’ I found 2 GitHub ‘issues’ threads that helped me figure out this problem.</p><ul><li><a href="https://github.com/rails/webpacker/issues/329#issuecomment-299977648">Upgrading from 1.0 to 1.2 caused a bunch of lint warnings · Issue #329 · rails/webpacker</a></li><li><a href="https://github.com/benmosher/eslint-plugin-import/issues/352#issuecomment-227820472">eslint-import-resolver-webpack don&#39;t work for resolved paths · Issue #352 · benmosher/eslint-plugin-import</a></li></ul><p>I think the issue is that we had to explicitly mention the environment so that it could pull in the proper dependencies. This seems to be unique to webpack<em>er.</em> Where webpack’s configuration file seems to have all config settings within it, webpack<em>er</em> has config settings broken into separate files. That’s why I changed the lint command to:</p><p>NODE_ENV=development yarn lint</p><p>That was the silver bullet to make our linter happy. Hopes this helps!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ed18a4669517" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>