<?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 Tinus Wagner on Medium]]></title>
        <description><![CDATA[Stories by Tinus Wagner on Medium]]></description>
        <link>https://medium.com/@ThatGuyTinus?source=rss-7de91c0df26c------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*k8nvJTcm-Pyn1WDE.jpg</url>
            <title>Stories by Tinus Wagner on Medium</title>
            <link>https://medium.com/@ThatGuyTinus?source=rss-7de91c0df26c------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 13:32:47 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@ThatGuyTinus/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[Random insights on Ruby Magic, learnt using express.]]></title>
            <link>https://medium.com/@ThatGuyTinus/random-insights-on-ruby-magic-learnt-using-express-3ac7fa6aa1e5?source=rss-7de91c0df26c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3ac7fa6aa1e5</guid>
            <category><![CDATA[express]]></category>
            <category><![CDATA[nodejs]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Tinus Wagner]]></dc:creator>
            <pubDate>Mon, 14 May 2018 13:08:08 GMT</pubDate>
            <atom:updated>2018-05-14T13:09:27.969Z</atom:updated>
            <content:encoded><![CDATA[<h4>Here’s some random thoughts strung together in no particular order.</h4><p>Throughout the last two years I’ve been a full-stack developer in the world of Ruby on Rails. I’ve dabbled in many front-end JS frameworks and tools. And sincerely grown to love JS in all it’s shapes and flavours. But even with the huge popularity of Node.js, I’ve never really given it a shot.</p><p>There’s a couple of reasons I dug in:</p><ol><li>To see what options are available to me outside of the Rails world, and how they compare.</li><li>It’s an opportunity to take a look at the noSQL world that seems to play so nicely with Node.js.</li><li>See what JS can really do in the backend world and how it stacks up to the wonderful experience that is Ruby on Rails development.</li></ol><h3>Getting started</h3><p>I already had MongoDB &amp; NodeJS (via NVM) installed so it was just a matter of updating them.</p><p>I did spend a bit of time looking around for a decent GUI for mongoDB but in the end I settled for the first option that I came across. MongoDB Compass seems to come highly recommended by the community, and while I have zero experience with it, as a frequent pgAdmin user I personally like the UI so far.</p><p>Make sure you grab the community edition :)</p><p><a href="https://www.mongodb.com/products/compass">MongoDB Compass</a></p><p>Now simply open a terminal window and run mongod . Once mongo’s up and running simply connect Compass to localhost and port specified by mongo.</p><h4>Express — My first impressions</h4><p>Now I’ve set up simple little servers before with express, but I’ve never really dealt with HOW the request/response cycle is laid out on a large scale, and I’m truly shocked by how simple it is to operate, especially once middleware like <a href="https://www.npmjs.com/package/body-parser">body-parser</a> starts playing a part.</p><p>Take the following for instance:</p><pre>const express = require(&#39;express&#39;);<br>const router = express.Router();</pre><pre>router.get(&#39;/&#39;, (req, res) =&gt; {<br>  res.send(&#39;pew&#39;);<br>});</pre><p>Sending a request tolocalhost:port allows you to immediately send a response using send but it’s capable of so much more. If you were to string params onto the string localhost:port/?name=&#39;dude&#39;&amp;age=&#39;100&#39; is easily accessible using req.query . Something that in the rails world I’d only really be able to grab onto from within the controller.</p><p>Similarly I can deal with variables in the url string quite simply by accessing the params of the request. The cool and flexible thing here is that since it’s just a regular JS function, you can grab these params and use them to manipulate your routing response. Completely independent of your controller.</p><pre>router.get(&#39;/reverse/:name&#39;, (req, res) =&gt; {<br>  const reverse = [...req.params.name].reverse().join(&#39;&#39;)<br>  res.send(reverse)<br>});</pre><p>Similarly I can with immediately respond with JSON using res.json {pew: &#39;pew&#39;, meow: &#39;mew&#39;} , and none of this is reliant on a controller to work!</p><p>Now all this is quite cool to me, in a rails application I’d have to define the route first, then a controller, and then define an action for that url before I’d be able to do these small menial things. Only then would I be able to inspect a query, manipulate params or serve up a JSON response.</p><pre>router.get(&#39;/&#39;, (req, res) =&gt; {<br>  res.render(&#39;hello&#39;, { myRelevantHashOfStuff });<br>});</pre><p>It’s not mind blowing or beyond comprehension, but I like the initial options express provides here for some very flexible routing logic.</p><p>Diving into express really starts to show you how much *<strong>rails magic</strong>* is occurring when a route is defined. So generally in a rails application you’d do the following to pass params via a url:</p><pre>config/routes.rb</pre><pre>Rails.application.routes.draw do<br>  resources :my_resource<br>end</pre><p>Which will magically give you access to every verb possible.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/50d02b55c2ec5317c428042185a7e1c7/href">https://medium.com/media/50d02b55c2ec5317c428042185a7e1c7/href</a></iframe><p>Then you’d create a controller</p><pre>app/controllers/my_resources_controller</pre><pre>class MyResourcesController &lt; ActionController::Base</pre><pre>  def my_verb<br>    ...do something<br>  end<br>end</pre><p>Now since this controller inherits from ActionController::Base, simply hitting that url with some random parameters and inspecting the request will show that you have a bunch of parameters that are available in a sensical way. All this just <em>happens.</em></p><p>Now once you set up an express route for that url and hit it with random params, not much useful will happen until you add some middleware such as a bodyParser. Similarly setting header content or perhaps adding a cookie to the response requires other middleware.</p><p>In the world of rails someone has made these decisions for you based on what <em>you’d probably need</em>. And 90% of the time they are right. The benefit of these sensible defaults is a very quick rate of initial development, but once things get more complicated it does limit your flexibility, or worse you start having to override default behaviour in ways you don’t fully comprehend, that have potential repercussions you may not have imagined.</p><p>A lot of these sensible defaults hide a substantial amount of complexity. And it’s a major gripe for some people since it makes rails development <em>noob friendly</em>. <a href="https://m.signalvnoise.com/conceptual-compression-means-beginners-dont-need-to-know-sql-hallelujah-661c1eaed983">It’s a form of conceptual compression and there is nothing wrong with that!</a></p><p>Interest will lead to exploration and eventually newcomers will start picking apart the pieces that peak their interest, but at least they won’t be alienated from joining the industry.</p><h4>Thanks for reading!</h4><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3ac7fa6aa1e5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Testing Thunk’d Async Action Creators with Mocha and Chai]]></title>
            <link>https://medium.com/@ThatGuyTinus/testing-thunkd-async-action-creators-with-mocha-and-chai-cf3c57cccafd?source=rss-7de91c0df26c------2</link>
            <guid isPermaLink="false">https://medium.com/p/cf3c57cccafd</guid>
            <category><![CDATA[react]]></category>
            <category><![CDATA[mocha]]></category>
            <category><![CDATA[chai]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Tinus Wagner]]></dc:creator>
            <pubDate>Mon, 23 Apr 2018 11:16:11 GMT</pubDate>
            <atom:updated>2018-04-23T11:16:11.688Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*RTwpkqiUB5vOO0MRSRycxQ.png" /><figcaption>We all love green squiggels</figcaption></figure><p>Woah what a title….</p><p>So every now (almost always) and then you’ll come across the need for an action creator that does something async, perhaps making an API request using <a href="https://github.com/axios/axios">axios</a>, which in turn opens up <a href="https://github.com/gaearon/redux-thunk">redux-thunk</a> as a middleware tool to deal with making these sorts of requests and dispatching actions based on the response.But testing these can get a bit messy. Here’s one solution.</p><h4>Learning by example</h4><ul><li>I have a server, which exposes a Signup API endpoint</li><li>My client app (a React/Redux app), contains a form that collects this data</li><li>OnSubmit it dispatches this data to an action creator called signUpUser</li><li>This function in turn executes an axios promise to our authentication endpoint.</li><li>It function takes in an email, and a password and on success returns a <a href="https://jwt.io/">JWT token</a></li><li>We will dispatch AUTH_USER and save the JWT token returned in localstorage on success</li><li>We will dispatch AUTH_ERROR if the response returned is an error</li></ul><p>So let’s assume you’ve got a component with a form up and running and doing it’s thing. Our action might look something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/451e287932877eccbbb1dc3d392e70db/href">https://medium.com/media/451e287932877eccbbb1dc3d392e70db/href</a></iframe><p>And now let’s import this action to our index.js file for a centralized point of contact for our tests. It’s kinda superficial for this post but once things grow, you’ll see why it’s important.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a13d1390c7a67c1f5467af6c8a5bac97/href">https://medium.com/media/a13d1390c7a67c1f5467af6c8a5bac97/href</a></iframe><p>And just for the sake of newcomers, our reducer might looks something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0a6def41c15968a162782e991131f2d0/href">https://medium.com/media/0a6def41c15968a162782e991131f2d0/href</a></iframe><p>Similarly let’s combine our reducers</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb371db0babaa422148664aa6a58cd67/href">https://medium.com/media/bb371db0babaa422148664aa6a58cd67/href</a></iframe><h4>Now how do we test this asyn’d stuff?</h4><p>Well let’s lay it out, we’ll need:</p><ul><li>A test runner. <a href="https://mochajs.org/">I’ll use Mocha</a></li><li>An assertion library. <a href="http://www.chaijs.com/">I’ll use Chai</a></li><li>Some way to stub LocalStorage since our action is setting localStorage, I’ll do it myself, <a href="https://www.npmjs.com/package/mock-local-storage">but npm probably has you covered</a>.</li><li>Some way to stub the Axios calls, <a href="https://www.npmjs.com/package/moxios">I’ll use moxios</a>.</li><li>We’ll need to import our thunk middleware to mock expected actions</li></ul><h4>Mocking Local Storage</h4><p>Now in this example we’ll need the worlds tiniest mock of localStorage but we can basically just create a function that returns the duplicated internal methods localStorage has available. In this case we’ll only need access to setItem (<a href="https://developer.mozilla.org/en-US/docs/Web/API/Storage/LocalStorage">you can read more about localStorage here</a>), but for a fully fleshed out action creator test suite you’ll probably need to also test a few other methods associated with localStorage. So here’s something to get you started.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/63d74966fdf22da9a34b03342c6e349b/href">https://medium.com/media/63d74966fdf22da9a34b03342c6e349b/href</a></iframe><p>Now testing an action creator isn’t too diffcult since :</p><p><em>In Redux, action creators are functions which return plain objects. When testing action creators we want to test whether the correct action creator was called and also whether the right action was returned.</em></p><p>Simply put we give it a type &amp; data, and we expect the action that was called to have the same type and a specific payload. So let’s setup our test.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/9ab736764fc52c3c41494ba63d1b0ce7/href">https://medium.com/media/9ab736764fc52c3c41494ba63d1b0ce7/href</a></iframe><p>And that’s one way to go about it!</p><h3>Thanks for reading!</h3><p>And if you see anything wrong, or that could be better, let me know! We’re all learning!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cf3c57cccafd" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[The unloved array methods of Javascript ? every : some]]></title>
            <link>https://medium.com/@ThatGuyTinus/the-unloved-array-methods-of-javascript-every-some-155148203bac?source=rss-7de91c0df26c------2</link>
            <guid isPermaLink="false">https://medium.com/p/155148203bac</guid>
            <category><![CDATA[es2015]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[es5]]></category>
            <dc:creator><![CDATA[Tinus Wagner]]></dc:creator>
            <pubDate>Thu, 12 Apr 2018 13:03:49 GMT</pubDate>
            <atom:updated>2018-04-13T08:45:07.295Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/500/1*cHLBQnjUyFHmnVwvVyp2nA.jpeg" /><figcaption>pretty much</figcaption></figure><p>Whenever I’m bored I randomly select a method or two to investigate, this time I came across the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some">some</a> and <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every">every</a> methods. But what’s a practical use case for them? Let’s break it down:</p><h3>Array.prototype.some</h3><p><em>The </em><strong><em>some()</em></strong><em> method tests whether at least one element in the array passes the test implemented by the provided function.</em></p><h3>Array.prototype.every</h3><p><em>The </em><strong><em>every()</em></strong><em> method tests whether all elements in the array pass the test implemented by the provided function.</em></p><h4>Use Case — Quick validations || sanity checking || testing method</h4><p>So in my opinion these methods can be quite useful in doing quick and dirty validation checks across collections.</p><ul><li>Checking if any item in a collection matches a minimum set of criteria.</li><li>Checking if a collection is valid. Does it contain nil or undefined valyes which could point to issues with code further up the chain.</li><li>Checking if a collection of relational objects contain <strong>at least </strong>point of reference.</li><li>Checking if a collection of relational objects contains any orphaned records, e.g. where a relationship could no longer be returned.</li><li>Checking if any item in a collection matches an array of values, e.g. do any of my users have [‘Admin’, ‘SuperAdmin’] as their account_type .</li></ul><h4>And here’s an example to illustrate a few of my points</h4><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83d160866b1b453d7dfcf1c294d301fa/href">https://medium.com/media/83d160866b1b453d7dfcf1c294d301fa/href</a></iframe><h3>Couldn’t I just use filter to do this?</h3><p>Well you sure can and for a very good reason, it’s universally a far more flexible and universally used method. But if your interest lies in in evaluating the<em> quality of an existing collection</em>, as opposed to <em>returning a new collection</em> <strong><em>every</em></strong><em> </em>and <strong><em>some</em></strong><em> </em>are definitely far more appropriate tools.</p><ul><li><strong><em>some</em></strong> will immediately return out of the method the moment an item in a collection <strong>meets some condition</strong>.</li><li><strong><em>every</em></strong><em> </em>will immediately return out of the method execution the moment an item in a collection <strong>does not meet some condition.</strong></li></ul><h3>Short and Sweet, thanks for reading!</h3><p>Let me know if you’ve come across any other nifty use cases for <strong>every/some!</strong></p><p>…or if you spot a mistake ;)</p><h4>Sources</h4><ul><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/every">Array.prototype.every() - JavaScript | MDN</a></li><li><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/some">Array.prototype.some() - JavaScript | MDN</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=155148203bac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A practical use of an inverted Index]]></title>
            <link>https://medium.com/@ThatGuyTinus/a-practical-use-of-an-inverted-index-38fa1cdff786?source=rss-7de91c0df26c------2</link>
            <guid isPermaLink="false">https://medium.com/p/38fa1cdff786</guid>
            <category><![CDATA[computer-science]]></category>
            <category><![CDATA[elasticsearch]]></category>
            <category><![CDATA[es6]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Tinus Wagner]]></dc:creator>
            <pubDate>Thu, 29 Mar 2018 10:07:31 GMT</pubDate>
            <atom:updated>2018-03-29T10:07:31.604Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/400/1*bsIQm6CB5wHooef2pAuT8g.jpeg" /><figcaption>…namaste</figcaption></figure><p>It’s amazing how much development you can do without ever really touching computer science topics. But our job as engineers (generally speaking), is to break complexity down into simple, manageable chunks.<strong> learning is no different</strong>. so I’ve taken it upon myself to at least peek into topics when I cross paths with them.</p><p>Recently I’ve been working with ElasticSearch quite a bit and come across inverted indexes.</p><h4>Warning!</h4><p>I’m absolutely amazed by the level of detail ElasticSearch’s documentation goes into on the topic, and I won’t be doing nearly as good a job of explaining the concept. Rather my approach is to skim the surface, and find a practical use for a concept that grabs my fancy. Definitely dig into the documentation for <a href="https://www.elastic.co/guide/en/elasticsearch/guide/current/full-text-search.html">full-text search and the use of inverted indexes.</a></p><h3>Where to start</h3><p>We’ll the full-text search feature of ElasticSearch is summarised as consisting of two aspects:</p><p><em>Relevance<br>The ability to rank results by how relevant they are to the given query (…)</em></p><p><em>Analysis<br>The process of converting a block of text into distinct, normalized tokens (see </em><a href="https://www.elastic.co/guide/en/elasticsearch/guide/current/analysis-intro.html"><em>Analysis and Analyzers</em></a><em>) in order to (a) </em><strong><em>create an inverted index and (b) query the inverted index.</em></strong></p><h3>Inverted Indexing — What is it?</h3><p>An inverted index is a method of breaking down documents/data/text into a list of unique items(a process sometimes referred to as tokenization), and for each respective item, creating a reference to its source. For example taking the sentences below we could craft an index list:</p><p><em>This sentence is our example text. it is mostly unique</em></p><p><em>An individual crafted our </em>exemplary<em> sentence.</em></p><pre>Term         Sentence1  Sentence2<br>---------------------------------<br>this         x          x <br>sentence     x          x<br>is           x          x<br>our          x          x<br>example      x          <br>text         x<br>it           x<br>mostly       x<br>unique       x<br>An                      x<br>individual              x<br>exemplary               x<br>crafted                 x</pre><p>Now as you can see if we were to search for the term <strong>sentence</strong> we’d be able to take these logical steps:</p><pre>1 -&gt; Query for our term(&#39;sentence&#39;)<br>2 -&gt; Reference to both sentences are found<br>3 -&gt; lookup and return both documents via reference<br>4 -&gt; do what we want with results</pre><p><strong>Consider this as the bare minimum example of the concept, just enough to lead you into our example if you know nothing about the topic.</strong></p><p>if you want to see how much work goes into making this concept function as well as it does in ElasticSearch, <a href="https://www.elastic.co/blog/found-elasticsearch-from-the-bottom-up">there’s a great series called Elastic Search from the bottom up.</a></p><h3>Our Example — Yaaaay Code</h3><p>Now let’s apply the concept to an example</p><ul><li>We have some sort of API we can use to make queries.</li></ul><p><em>The API allows us to pass a </em><em>string as our query and an </em><em>array as the attributes to look in for the specified string. So let’s say our request is:</em></p><pre>api/search?q=&#39;bla&#39;&amp;in[]=&quot;name&quot;&amp;in[]=&quot;desc&quot;&amp;in[]=&quot;topic&quot;</pre><ul><li>A collection is returned along with a field that tries to calculate the likelihood of match, for our search term, across all attributes provided.</li></ul><pre>let results = [<br>  {id: 1, name: &quot;b&quot;, desc: &quot;b&quot;, topic: &quot;bla&quot;, match: 0.33},<br>  {id: 2, name: &quot;bla&quot;, desc: &quot;b&quot;, topic: &quot;b&quot;, match: 0.33},<br>  {id: 3, name: &quot;b&quot;, desc: &quot;bla&quot;, topic: &quot;b&quot;, match: 0.33}<br>]</pre><pre>For search term &quot;bla&quot; in [&#39;name&#39;,&#39;description&#39;,&#39;topic&#39;]. we get three matches in three seperate fields. meaning each results has an equal likelihood of being most accurate match.</pre><ul><li>We decide for whatever reason that a match found in one attribute might be more important than another.</li></ul><p><em>For example, articles with the topic of </em><em>animals will in all likelihood return the most accurate results for a user looking for articles about animals, descriptions fields will in all likelihood return the least accurate.</em></p><ul><li>So we decide to rank or weight the priority of our fields, so matches found in more important fields are ranked higher. In the end we create an index list for this:</li></ul><pre>let lookup_table = [<br>  { property: &#39;name&#39;, weight: 0.3 },<br>  { property: &#39;topic&#39;, weight: 0.5 },<br>  { property: &#39;desc&#39;, weight: 0.2 }<br>]</pre><h3>Let’s do this</h3><p>Ok so there’s a few things we’ll need to do here, and I’m going to go through them step-by-step, and function by function, then we’ll tie it all together:</p><pre>1. Loop through collection and determine in which attributes a matches were found<br>2. Take that attribute and lookup it&#39;s weighting in our lookup table<br>3. calculate the weighted match value for each item<br>4. return them in the correct order with weighting applied</pre><ol><li>Determine attribute where match was found in</li></ol><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/37b74cf9a94f7fde2be4e882e1f90efe/href">https://medium.com/media/37b74cf9a94f7fde2be4e882e1f90efe/href</a></iframe><ul><li>Map each key from our object to an array using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys">Object.keys</a></li><li>Use <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/find">array.find</a> to search through our object and return the key/attribute where match was found.</li></ul><p><strong>2.</strong> Take that key/attribute and lookup it’s weighting in our lookup table.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a0d2ee36a25a3250c68bb0d5ff4b399e/href">https://medium.com/media/a0d2ee36a25a3250c68bb0d5ff4b399e/href</a></iframe><ul><li>Now that we have the key we dive into our lookup_table to find the respective weight.</li></ul><p><strong>3. </strong>Apply the weighting to our results</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b49143c85f9c17a8c761575f577dce42/href">https://medium.com/media/b49143c85f9c17a8c761575f577dce42/href</a></iframe><p><strong>4. </strong>Sort our matches from highest to lowest</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/871865b438590fd90625ac630b774c70/href">https://medium.com/media/871865b438590fd90625ac630b774c70/href</a></iframe><ul><li>using the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/sort">compareFunction of Array.sort</a> allows us to do a nice little numerical comparison to sort in our desired order.</li></ul><h3>Annnnd All together…</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f0c34cd388ee65e2b5cc303ee111264/href">https://medium.com/media/6f0c34cd388ee65e2b5cc303ee111264/href</a></iframe><h4>Or on codepen for your pleasure.</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Ftinusw%2Fembed%2Fpreview%2FqopMZd%3Fheight%3D600%26slug-hash%3DqopMZd%26default-tabs%3Djs%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io%26embed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Ftinusw%2Fpen%2FqopMZd%3Feditors%3D0012&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F630410.qopMZd.small.635b90d1-8fce-4919-864e-afe5054228f9.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd5ea64f532ef5c2939778fcc1dd78b2/href">https://medium.com/media/cd5ea64f532ef5c2939778fcc1dd78b2/href</a></iframe><p>A practical use of an inverse index to apply a weighting to a collection of results!</p><h3>Yell out if you spot any mistakes or inconsistencies!</h3><p>I’m constantly learning, feel free to be a part of that process :)</p><p>Thanks for reading!</p><h4>Source Material &amp; More to read</h4><ul><li><a href="https://www.elastic.co/guide/en/elasticsearch/guide/current/inverted-index.html">On inverted indexing specifically (…and where I stole my explanation of it)</a></li><li><a href="https://www.elastic.co/guide/en/elasticsearch/guide/current/full-text-search.html">The cool-nes that is full text search</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=38fa1cdff786" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[5 common JS quiz questions]]></title>
            <link>https://medium.com/@ThatGuyTinus/5-common-js-quiz-questions-b71c18281de4?source=rss-7de91c0df26c------2</link>
            <guid isPermaLink="false">https://medium.com/p/b71c18281de4</guid>
            <category><![CDATA[coding-interviews]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[Tinus Wagner]]></dc:creator>
            <pubDate>Thu, 22 Mar 2018 17:03:09 GMT</pubDate>
            <atom:updated>2018-03-22T17:03:09.543Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/750/1*Hyu8thcs0tABwDKZJhBRkA.jpeg" /></figure><p>I don’t know about the rest of you, but the interview tests generally scare the crap out of me. I’ve built quite a few things over the last two years that I’m truly proud of, but whenever the interview process heads down this road I always feel my nerves bubbling up.</p><p>So let’s dive into some common questions and solve em:</p><h3>1) Make this statement work</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f902857ea3c0506471b8f54e4290142e/href">https://medium.com/media/f902857ea3c0506471b8f54e4290142e/href</a></iframe><p>Now my first instinct is simply to grab my array and concatenate by writing a little function. But that doesn’t really answer the question and shows how easily nerves can lead you in the wrong direction.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e42b8acd373401e052ae33d2157afd92/href">https://medium.com/media/e42b8acd373401e052ae33d2157afd92/href</a></iframe><p>this works BUT DOESN’T MAKE THE STATEMENT WORK</p><p>What you really want to do is dig into the Array constructor, in other words, you want to add a duplicator method to the object used to construct <strong>ALL ARRAYS.</strong></p><p>To do this you need to dive into <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/prototype">Array.prototype</a> which</p><p><em>...</em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array"><em>Array</em></a><em> instances inherit from </em><em>.... As with all constructors, you can change the constructor&#39;s prototype object to make changes to all </em><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array"><em>Array</em></a><em> instances. For example, you can add new methods and properties to extend all </em><em>Array objects.</em></p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23f5dcc19e143a831572a9bcfbe018ad/href">https://medium.com/media/23f5dcc19e143a831572a9bcfbe018ad/href</a></iframe><p>We extend the core Array object with a method called duplicator</p><p><strong>Don’t try to get fancy here as the ES6 arrow function </strong><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions"><em>does not have its own </em></a><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions"><em>this, arguments, super, or new.target. (…), and they cannot be used as constructors.</em></a></p><h4>2) Fizz-Buzz</h4><p><em>Write a program that prints the numbers from 1 to 100. But for multiples of three print “Fizz” instead of the number and for the multiples of five print “Buzz”. For numbers which are multiples of both three and five print “FizzBuzz”.</em></p><p>This tests your knowledge of <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Expressions_and_Operators">operators (or one operator) ever so slightly</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ca156bd50242fc436ad8df4a19d5872/href">https://medium.com/media/0ca156bd50242fc436ad8df4a19d5872/href</a></iframe><p>There’s a million ways to solve this one. But this solution does have a problems with repetition aaaaaaaaaand if we’d change the order of execution and place the 3 &amp; 5 comparison last in the loop, it will never be executed. So let’s try again.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b5b7eb01813ca1dfc9d12c986056424d/href">https://medium.com/media/b5b7eb01813ca1dfc9d12c986056424d/href</a></iframe><ul><li>We can DRY up this loop by saving the outcome of our comparison in a var and then simply printing/logging our output at the end of our loop.</li><li>we can pull out our else statements since this will achieve the same purpose regardless</li><li>By saving the fizz/buzz output to a variable we can easily concatenate the string if both conditions are met which allows us to do away with an modulo comparison.</li></ul><p>While looking at the hundreds of ways to solve FizzBuzz <a href="https://codeburst.io/javascript-breaking-down-the-shortest-possible-fizzbuzz-answer-94a0ad9d128a">I stumbled on this post</a>. Which broke down the shortest version of FizzBuzz I’ve ever seen, and in a way that doesn’t deviate to much from our second solution once you break it down.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a7077db71be447c4f562e6a5b4831e8/href">https://medium.com/media/6a7077db71be447c4f562e6a5b4831e8/href</a></iframe><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Conditional_Operator">Ternary Operators!</a> That’s the secret here, each loop compares i to our conditions and either appends an empty string, or fizz or buzz. If no condition is matched, it simply returns i. And since all this already happens in a console.log, the content is printed.</p><h3>3) How would you make this work?</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/d9a8e061e2632cbfc7e674d4768dbf11/href">https://medium.com/media/d9a8e061e2632cbfc7e674d4768dbf11/href</a></iframe><p>This is quite an interesting one that I hadn’t come across before. In the first example add is obviously a function that returns the sum of both arguments. But we’ve the second examples makes use of a secondary set of brackets which are a bit WTF.</p><p>This is an example of a function, that internally calls itself. And when you really think it through it makes sense if the first executions value is saved as an variable internally, or intermediate variable. So we could visualise it like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/339b99998678f5ffe26af33623750b75/href">https://medium.com/media/339b99998678f5ffe26af33623750b75/href</a></iframe><p><a href="https://stackoverflow.com/questions/17982637/syntax-of-closures">I credit this stackoverflow answer for helping me <em>get it.</em></a><em> </em>What we’re really dealing with here is the <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures">concept of closures</a> which is</p><p><em>…the combination of a function and the lexical environment within which that function was declared.</em></p><p>Now that we understand that a closure is a combination of the function and the environment it is executed in we can do away with our intermediate variable since we understand that the secondary internal call of the function has access to a difference environment than the first, whereby the <strong>first argument becomes available for use within the second function call</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1cf731474bdd8550af38c22cab1b7742/href">https://medium.com/media/1cf731474bdd8550af38c22cab1b7742/href</a></iframe><p><a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Closures">I’d recommend reading the practical use of closures section on MDN to get a feel for where they may be useful.</a></p><p>So now we can solve both use cases with one function by merging our approaches, by internally checking how many arguments are supplied, and conditionally executing a sum on the secondary set of brackets.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b9bc0f594c0fbb3ee93fe06ad81b1168/href">https://medium.com/media/b9bc0f594c0fbb3ee93fe06ad81b1168/href</a></iframe><p><em>When a function is invoked, JavaScript does not require the number of arguments to match the number of arguments in the function definition. If the number of arguments passed exceeds the number of arguments in the function definition, the excess arguments will simply be ignored.</em></p><h3>4) Implement your own Array flatten method</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/043f63b55ebda8e14351920d66166ac8/href">https://medium.com/media/043f63b55ebda8e14351920d66166ac8/href</a></iframe><p>But we can simplify this even further using <a href="https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Array/Reduce">reduce</a> to run a function against each value in the index.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5197445a888dc40a79f21173eb030bd4/href">https://medium.com/media/5197445a888dc40a79f21173eb030bd4/href</a></iframe><h3>5) Will the following statements return True or False?</h3><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c5df80e2a0536fc47424c4653ca58b5b/href">https://medium.com/media/c5df80e2a0536fc47424c4653ca58b5b/href</a></iframe><p>This is quite a interesting little question since it deals with the order of execution.</p><p>As expected the first statement evaluates to true, however the second returns false because javascript. Comparison is done from left to right so in the end what’s really compared here is true &gt; 1which evaluates to false</p><h4>Thanks for reading!</h4><h3>Hey Tinus, that’s not a great solution to XYZ</h3><p>Sweet, feel free to let me know!</p><h3>Hey Tinus, you can ES6/7/8/22/101 that using XYZ</h3><p>Sweet, feel free to let me know!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b71c18281de4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Exploring CSS Grid : An Introduction to my new favourite layout property.]]></title>
            <link>https://medium.com/@ThatGuyTinus/exploring-css-grid-an-introduction-to-my-new-favourite-layout-property-a25592279c16?source=rss-7de91c0df26c------2</link>
            <guid isPermaLink="false">https://medium.com/p/a25592279c16</guid>
            <category><![CDATA[css]]></category>
            <category><![CDATA[responsive-web-design]]></category>
            <dc:creator><![CDATA[Tinus Wagner]]></dc:creator>
            <pubDate>Thu, 31 Aug 2017 15:57:22 GMT</pubDate>
            <atom:updated>2017-08-31T15:59:31.922Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BFAbEQ3D07gH4C53ndxVdw.jpeg" /><figcaption>Mozilla has the best documentation on this</figcaption></figure><p>I’ve recently come across the <a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout">CSS grid layout</a>, and to put it lightly, it’s kinda blown my mind. So I thought I’d do a little dive into what you could achieve in half an hour using it.</p><h4>First things first…</h4><p>The concept of wrapping things in rows and containers is almost so second nature to me that I never even wondered why we go through these pains to get content aligned the way we want to. There’s always an edge-case that bootstrap can’t resolve, or a design decision that just doesn’t translate well on your grandmothers computer when she uses internet explorer.</p><p>Inevitably you end having to customise a padding or a margin somewhere, and then you end up having to constantly re-test many of the responsive layouts bootstrap already resolved for you, and you essentially may have broken :(</p><p><a href="https://www.youtube.com/watch?v=7kVeCqQCxlk">Then I came across this great talk by Morten Rand-Hendriksen</a> digging into CSS Grid, which is officially live in all good browsers.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*74HKJKOLb0nzD3H2NwghBw.png" /></figure><p>Now Morten sells it pretty strongly by claiming that it’s <strong>“a whole new way of thinking about layouts(…), that will truly change the way we design websites from here on forward.”. </strong>His talk will probably do a better job of explaining CSS grid than this post so <a href="https://www.youtube.com/watch?v=7kVeCqQCxlk">I highly recommend you watch it!</a></p><p>But let’s look at a sample:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Ftinusw%2Fembed%2Fpreview%2FEvGrgb%3Fheight%3D600%26slug-hash%3DEvGrgb%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io%26embed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Ftinusw%2Fpen%2FEvGrgb&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F630410.EvGrgb.small.eca24bff-d214-4d46-94e4-7f5a103cbcc1.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/bda7cfb0349e685548f76db8d189de7a/href">https://medium.com/media/bda7cfb0349e685548f76db8d189de7a/href</a></iframe><p>Here we have 6 divs all laid out across the page in a variety of ways. Yet our HTML markup only requires one wrapping div to ensure we set the layout to <strong>grid. </strong>No Crazy floats or columns and rows…</p><p>Then we essentially select how many rows we’d like using the gird<a href="https://developer.mozilla.org/en-US/docs/Web/CSS/grid-auto-rows"> auto rows property</a> we’d like the grid to contain. Then finally in each div we simply specific which rows and columns of the grid we’d like the div to occupy (I guess columns are dynamically set as you specific them in your element).</p><pre>.one {<br>  border: solid green;<br>  grid-column: 1 / 3;<br>  grid-row: 1;<br>}</pre><pre>.two {<br>  border: solid blue;<br>  grid-column: 2 / 4;<br>  grid-row: 1 / 3;<br>}</pre><h4>What does this mean for responsive design?</h4><p>Well essentially a hell of a lot. We basically have the ability to define unique grids for each breakpoint, and simultaneously specify what portion of the grid each element should populate for the given media query. This means massively simplified layouts and markup even when dealing with complex layouts! You can even define a grid layout and within a certain element of an existing grid element (grid-ception)!</p><h4>I find this super exciting</h4><p><a href="https://codepen.io/tinusw/pen/PKKMQY">If you’re still not sure take a look on the code pen below on a nice big screen, (I’d open it in a new window as a lot of the breakpoints won’t kick in on the page):</a></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fcodepen.io%2Ftinusw%2Fembed%2Fpreview%2FPKKMQY%3Fheight%3D600%26slug-hash%3DPKKMQY%26default-tabs%3Dcss%2Cresult%26host%3Dhttps%3A%2F%2Fcodepen.io%26embed-version%3D2&amp;url=https%3A%2F%2Fcodepen.io%2Ftinusw%2Fpen%2FPKKMQY&amp;image=https%3A%2F%2Fs3-us-west-2.amazonaws.com%2Fi.cdpn.io%2F630410.PKKMQY.small.6101cd31-171b-4779-a15e-e0275f6e3bbb.png&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=codepen" width="800" height="600" frameborder="0" scrolling="no"><a href="https://medium.com/media/348509b239f61495a97cfd002ed17ff3/href">https://medium.com/media/348509b239f61495a97cfd002ed17ff3/href</a></iframe><p>I’ve defined 9 different breakpoints and implemented varying layouts for each one. So if you grab your browser and swipe through screen sizes you should get a good idea of the potential this has for building layouts with nothing but good old CSS!</p><p><a href="https://developer.mozilla.org/en-US/docs/Web/CSS/CSS_Grid_Layout">I recommend the MDN documentation for further mind-blowing reading.</a></p><p>Thanks for reading and let me know what you think!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a25592279c16" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stripe Connect & Rails — Part 3]]></title>
            <link>https://medium.com/@ThatGuyTinus/stripe-and-rails-part-3-63e22abde900?source=rss-7de91c0df26c------2</link>
            <guid isPermaLink="false">https://medium.com/p/63e22abde900</guid>
            <category><![CDATA[stripe]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[stripe-api]]></category>
            <category><![CDATA[payments]]></category>
            <category><![CDATA[rails]]></category>
            <dc:creator><![CDATA[Tinus Wagner]]></dc:creator>
            <pubDate>Sun, 11 Jun 2017 06:32:55 GMT</pubDate>
            <atom:updated>2017-06-11T06:36:22.415Z</atom:updated>
            <content:encoded><![CDATA[<h4>This is Part 3 of my series on integrating Stripe Connect into a ruby on rails application</h4><p><a href="https://medium.com/@ThatGuyTinus/stripe-connect-rails-part-1-22ba7204725b"><em>Read part 1 here</em></a></p><p><a href="https://medium.com/@ThatGuyTinus/stripe-connect-rails-part-2-9751c0e553f9"><em>Read part 2 here</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/960/1*q7c_ZB_XNyjuSEIU-4RJKg.jpeg" /></figure><h4>Moving on!</h4><p>So in <a href="https://medium.com/@ThatGuyTinus/stripe-connect-rails-part-2-9751c0e553f9">Part 2</a> we built a simple little application using Stripe Connect. We now have merchants and customers freely transacting and making payments. In the final part of our series we’ll allow our platform to:</p><ul><li>Charge a fee for purchases, and make some money!</li><li>Credit our users, allowing them to purchase goods at reduced prices!</li></ul><h4>Charging a fee</h4><p>First things first, let’s generate a migration to add the fee field to each of our merchants, and a field to track fee’s charged on transactions.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5cb9a05c1a032c21880ea533e795558f/href">https://medium.com/media/5cb9a05c1a032c21880ea533e795558f/href</a></iframe><p>P.S. if you plan on changing fee percentages often, it may be worth saving the fee in your transaction record as well for historical accuracy!</p><p>Once this has been migrated let’s add it to our admin view &amp; controller, and create a little form with a PUT action to set a fee.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3bf892dd60af78974b244f3030a3d760/href">https://medium.com/media/3bf892dd60af78974b244f3030a3d760/href</a></iframe><p>And our view</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4722790eb63d16efea66e3609f9b1679/href">https://medium.com/media/4722790eb63d16efea66e3609f9b1679/href</a></iframe><p>let’s set a little model method to handle updating this attribute:</p><pre>def set_fee(amount)<br>  update_attribute(:fee, amount)<br>end</pre><p>We’ll also need to update our merchant controller to be able to deal with a record being updated from two forms on two seperate pages, and with seperate parameters. So let’s dive into our update action and add some conditional routing.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ea2e03d1985573093936ace78558cab0/href">https://medium.com/media/ea2e03d1985573093936ace78558cab0/href</a></iframe><p>Awesome, now our admins can set a fee for each individual merchant.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*V8_wFP_L0BQz1WYeMSJ5jw.gif" /></figure><p>Let’s string this onto our Stripe Charge.</p><p>The first thing we’ll need to do is convert our fee <a href="https://stripe.com/docs/api#charge_object">(Which Stripe refers to as an </a><a href="https://stripe.com/docs/api#charge_object">application_fee</a>) to a percentage out of 100, which we can then string it into our existing Stripe::Charge.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e531d46350cdf79b1449c692240f3f91/href">https://medium.com/media/e531d46350cdf79b1449c692240f3f91/href</a></iframe><p>So if we try to purchase something now we should see something like this on success:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cHdoHMF68EfwyFldCft2-A.png" /></figure><p>We should also be able to confirm this from within Stripe if we look up that specific charge.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Jv0xb1vDdXPiqFzq5oX6Rw.png" /></figure><h3>And That’s Fees sorted! It’s that simple!</h3><p>Next up</p><h3>Crediting Users</h3><p>You may have noticed that we already have a few things in place for this functionality. We have:</p><ol><li>In the admin view a button to credit a user with $10.00</li><li>A field in the users records tracking the amount credited.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*EUbiAq5Hn02ugY-D7jCrpg.gif" /><figcaption>A very popular tactic for spending VC money ;)</figcaption></figure><p>So to tackle this within a stripe charge we need to:</p><ol><li>First check if a user has credit</li><li>Determine if the user has enough credit to cover the entire charge</li><li>Or whether it is only going to be partially covered by credit, and we’re supposed to split the charge into two charges!</li></ol><p>The credited portion (which is covered by the users credit), should be paid by the <strong>marketplace, and not charged a fee (why would we charge ourselves a fee?)</strong></p><p>The remainder should be paid by the user as normal, and thereafter, we should update how much credit the user has left.</p><p><em>P.S. Stripe has a </em><a href="https://support.stripe.com/questions/what-is-the-minimum-amount-i-can-charge-with-stripe"><em>minimum charge amount which is varies by currency</em></a><em>, but for the sake of our USD based example it’s $0.50.</em></p><p>So the first thing we need to do is register a credit card associated with our platform, This is where an admin account comes in useful.</p><p>So grab the old company card, and register as a customer with that card. Once you’ve successfully done that, grab the customer_id of the admin user and save that in our .env file as our MASTER_CREDIT_ACCOUNT. <strong>When the user has credit and the platform needs to cover the credited portion of a transaction, this is the account we will use.</strong></p><p>Now we need to start refactoring our transaction.rb model file to first check if the user has credit, if he the user does have credit:</p><ol><li>Is it enough to cover the entire charge?</li><li>Is it enough to cover a portion of the charge</li><li>If a portion is covered, what is the remainder we need to charge the user?</li></ol><p>So let’s start refactoring our transactions model</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9f82e9b266827623c1cdd7204e704a2/href">https://medium.com/media/c9f82e9b266827623c1cdd7204e704a2/href</a></iframe><p>Basically,</p><ul><li>if the user has no credit, we make a <strong>regular charge</strong>.</li><li>If the user does have credit, we see how much.</li><li>If it’s enough to cover the entire charge, we make a single payment from the MASTER_CREDIT_ACCOUNT.</li><li>If not, then we split the payment into two charges.</li><li>If the charge was covered by the user, we’ll update the transaction record to reflect that</li><li>If the charge was covered by the platform, we’ll update the transaction record to reflect that.</li><li>We also render an alternate description within our charge if a credited transaction has occurred, so we can reconcile that to the original purchase.</li></ul><h4>So if a charge is totally covered by credit:</h4><p>Our application will visualise this as follows:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DHgN3PEW3lXj3HC8Z03PzQ.png" /></figure><p>If we then check in Stripe we’ll see the following</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*6hogDkK1aDjpPsH8FOQwhQ.png" /><figcaption>Note that the fee here is the Stripe processing fee, not our application_fee</figcaption></figure><h4>If a charge is partially covered by credit</h4><p>Our users will only be charged the portion that credit doesn’t cover, and we will charge a fee based on this remaining amount.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tOZBbv_zqjBaNehz8sBQ2g.png" /></figure><p>If we now check stripe, we’ll see two separate charges:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*OjNCUXvJW7k0bq2EcZDqag.png" /></figure><p>The credited charge :</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Cg_ewbhuNbNELtxm7cr1Rg.png" /></figure><p>And the remainder with an application fee</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*9ywtBKFm-1veDMs3wKm9aA.png" /></figure><h4>Finally, a regular charge</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*U5R9eKMWvyIHRdNN6BRgEA.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*-rzCowmUdThvPnhNNsO80A.png" /></figure><h3>And there you have it!</h3><p>Congrats! You’ve now set up Stripe Connect to charge a platform fee, and you’re able to credit users with a bit of startup money to get them spending!</p><p>Well done, and thanks for reading.</p><p>Please get in touch if you’ve spotted any significant errors or mistakes! I’m only human!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=63e22abde900" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stripe Connect & Rails — Part 2]]></title>
            <link>https://medium.com/@ThatGuyTinus/stripe-connect-rails-part-2-9751c0e553f9?source=rss-7de91c0df26c------2</link>
            <guid isPermaLink="false">https://medium.com/p/9751c0e553f9</guid>
            <category><![CDATA[jquery]]></category>
            <category><![CDATA[stripe-connect]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[stripe]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Tinus Wagner]]></dc:creator>
            <pubDate>Sat, 03 Jun 2017 08:53:14 GMT</pubDate>
            <atom:updated>2017-06-11T06:35:13.576Z</atom:updated>
            <content:encoded><![CDATA[<h4>This is Part 3 of my series on integrating Stripe Connect into a ruby on rails application</h4><p><a href="https://medium.com/@ThatGuyTinus/stripe-connect-rails-part-1-22ba7204725b"><em>Read part 1 here</em></a></p><p><a href="https://medium.com/@ThatGuyTinus/stripe-and-rails-part-3-63e22abde900"><em>Read part 3 here</em></a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*O1svlesV3a28TXQn5uthEA.png" /><figcaption>love your work stripe!</figcaption></figure><h4>Moving on!</h4><p>In <a href="https://medium.com/@ThatGuyTinus/stripe-connect-rails-part-1-22ba7204725b">Part 1</a> we discussed all the pieces of the Stripe Connect puzzle, now it’s time to build something.</p><h3>The Idea</h3><p>We’re going to build a small marketplace application with the <br>following features:</p><ol><li>Users can sign up, and list items for sale as a Merchant</li><li>Users can sign up, and buy items as customers.</li><li>Users can then review their transactions once completed</li><li>Our App will process payments using the Stripe Connect platform</li><li>Our Marketplace can charge individual merchants a dynamic fee.</li><li>Our Marketplace can credit users to incentivise buying.</li></ol><p>Now since this tutorial is about setting up Stripe connect and not about building an application, I’ve taken the liberty of setting up a very rough &amp; ready application starting point for you.</p><p><a href="https://github.com/Tinusw/StripeMarketplace/tree/097d269f18e49e59e901f5f7860a32fbd08745f2">You can download it here if you want to follow along</a></p><h3>Getting Started — Connecting Merchants</h3><p>Our first concern should be making sure our merchants are connected to their stripe accounts so that they can receive payments.</p><p>We’ll have a few Stripe related keys we’ll need to deal with so let’s set up <a href="https://github.com/bkeepers/dotenv">dotenv</a> and create a .env file. Here’s what we’ll need:</p><pre># STRIPE_KEYS (found in stripe settings)<br># Publish and Secret keys are account specific<br>PUBLISHABLE_KEY=&quot;pk_test_xxxxxxxxxxxxxxxxx&quot;<br>SECRET_KEY=&quot;sk_test_xxxxxxxxxxxxxxxxx&quot;</pre><pre># Client ID is application specific (found in Stripe Account that is hosting the platform under connect settings)<br>CLIENT_ID=&quot;ca_xxxxxxxxxxxxxxxxx&quot;</pre><pre># Master Account<br># The Stripe Account attached to your admin or business<br># When users have credit, this is the account that will be charged instead <br>MASTER_CREDIT_ACCOUNT=&quot;cus_xxxxxxxxxxxxxxxxx&quot;</pre><p>Now let’s setup a few more fields in our Merchants table to prepare for this:</p><pre>class AddStripeFieldsToMerchant &lt; ActiveRecord::Migration[5.0]<br>  def change<br>    add_column :merchants, :uid, :string<br>    add_column :merchants, :provider, :string<br>    add_column :merchants, :access_code, :string<br>    add_column :merchants, :publishable_key, :string<br>  end<br>end</pre><p>Now we’re going to have these fields populated by a callback from stripe using omniauth, so we’ll need the <a href="https://github.com/isaacsanders/omniauth-stripe-connect">omniauth-stripe-connect gem</a> to get this up and running.</p><p>Let’s head over to our config/initializers/devise.rb file and add the configuration that will consume our environment variables, set omniauth’s rights, and set the landing page that users will see once stripe routes them away from the application.</p><pre>config.omniauth :stripe_connect,<br>  ENV[&#39;CLIENT_ID&#39;],<br>  ENV[&#39;SECRET_KEY&#39;],<br>  scope: &#39;read_write&#39;,<br>  stripe_landing: &#39;login&#39;</pre><p>Let’s also go ahead and create config/initializers/stripe.rb to help us consume these keys within our application.</p><pre>Rails.configuration.stripe = {  <br>  :publishable_key =&gt; ENV[&#39;PUBLISHABLE_KEY&#39;],  <br>  :secret_key      =&gt; ENV[&#39;SECRET_KEY&#39;]<br>} <br>Stripe.api_key = Rails.configuration.stripe[:secret_key]</pre><p>The next thing we need is a controller for the omniauth callback, that will inherit from devise.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0ec4a0fff6b8de193c6418a44396da10/href">https://medium.com/media/0ec4a0fff6b8de193c6418a44396da10/href</a></iframe><p>Now we have to add our omniauth controller into our devise routes:</p><pre>devise_for :users, controllers: {<br>  omniauth_callbacks: &#39;omniauth_callbacks&#39;<br>}</pre><p>and into our User model for devise to consume, as well as a few methods to check if the user is set up to receive payments:</p><pre>class User &lt; ApplicationRecord<br>  devise :database_authenticatable, :registerable,<br>         :recoverable, :rememberable, :trackable, :validatable, :omniauthable, :omniauth_providers =&gt; [:stripe_connect]</pre><pre>  def is_seller?<br>    merchants.any?<br>  end</pre><pre>  def can_receive_payments?<br>    uid? &amp;&amp;  provider? &amp;&amp; access_code? &amp;&amp; publishable_key?<br>  end</pre><p>So these two methods basically give us a few triggers to check if a user is a merchant, and if that user has already registered their business on the Stripe Connect platform.</p><p>We should now have everything we need…except for a url to call to go out to stripe, so let’s set up a little helper method in helpers/application_helper.rb</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82cb02b11bc34ab0452a7593f69c1c7d/href">https://medium.com/media/82cb02b11bc34ab0452a7593f69c1c7d/href</a></iframe><p>Now let’s put something into our root_page to make all this magic happen. Add the following on views/merchants/index</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d2f62063ac724884586c5737ea41e54/href">https://medium.com/media/5d2f62063ac724884586c5737ea41e54/href</a></iframe><p>And let’s also check out our views/merchants/show page to make sure items are only visible for purchase, <strong>IF</strong> the merchant can receive payments via Stripe (e.g. they’ve connected a bank account to our Application, via Stripe).</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b302cd2b025fc70b8f77cfe5090adc27/href">https://medium.com/media/b302cd2b025fc70b8f77cfe5090adc27/href</a></iframe><h3>That was effort!</h3><p>Sure was, but we’re just about there! Head on over to your connect Settings tab and make sure you set a Redirect URI for our Stripe Omniauth call, else there will be nowhere for the response data to go!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jkRbkLipEXBhOVdHSmqBbw.png" /><figcaption>You’ll see a lot more info which I’ve edited out</figcaption></figure><p>And Finally, I’d recommend creating a test account within Stripe, which we can then use as our ‘Merchants’ account. Once you’ve set that up go ahead and click on our stripe button to get routed to the Stripe Connect page.</p><p>Now if you’re not signed in, you’ll need to do that first (or create an account if you haven’t already). But you’ll see something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/961/1*4adbdapWEDplLFjbsPuFiQ.png" /><figcaption>We are interested in the top development bar!</figcaption></figure><p>Thankfully we’re in development and using development keys, so we can skip the whole signing up our business process and return a some fake test details. Keep an eye on your database when this after clicking this to see the callback in action!</p><h3>Great Success! I’m a business on Stripe!</h3><p>Let’s query our user in the console to see if they’ve got a UID number</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/813/1*epGn_OvK1R8zrj7KJhAfKA.png" /><figcaption>we’re looking for acct_1AO0vmF8x1kAQC6x</figcaption></figure><p>And now let’s double check that in our stripe Master account!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hfJNl6JsytqaCZi5aJ17Kw.png" /><figcaption>Our merchants Stripe Account is connected!</figcaption></figure><p>Nice work, you (as a merchant) can now receive payments!, now for the guests portion of the puzzle. Which thankfully we can take care of using <a href="https://stripe.com/docs/stripe.js?">Stripe.js</a>.</p><h4>Stripe JS</h4><p>Stripe JS is a nice little JS function that allows us to consume a users credit card details and have them verified by Stripe. We don’t save any credit card details ourselves, but stripe sends us back a token, that we can use to create a Customer Object! Essentially registering our users as customers who use our platform, but without having to save any card details ourselves, nor deal with the Rules and Regulations that are intertwined with that stuff.</p><p>So let’s start off by including stripe.js in the head of ourlayouts/application.haml</p><pre>%script{src: &quot;<a href="https://js.stripe.com/v2/">https://js.stripe.com/v2/</a>&quot;, type: &quot;text/javascript&quot;}</pre><h4>Gon</h4><p>Stripe JS will also rely on one of our API keys to authenticate the request, so lets add the <a href="https://github.com/gazay/gon">gon gem, so we get our rails variables as a JS object</a>. After you’ve installed it head over to your layouts/application.haml and add gon in.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e0e4c41ecaa9c394ca95c5d28ae2bf3c/href">https://medium.com/media/e0e4c41ecaa9c394ca95c5d28ae2bf3c/href</a></iframe><p>To get Gon to actually spit out the key that we need, head over to controllers/application_controller.rb and assign the key to a gon variable.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f42054ea96446bc163d4847816c0b75f/href">https://medium.com/media/f42054ea96446bc163d4847816c0b75f/href</a></iframe><p>P.S. Don’t forget to restart your server after this. Gon won’t do a thing since it’s only initialized during startup.</p><h4>Migration Time</h4><p>Then we need a new migration to save a users stripe_customer_id, basically a reference to their credit card. Once it’s returned to us by Stripe.js</p><pre>class AddStripeCustomerIdToUsers &lt; ActiveRecord::Migration[5.0]<br>  def change<br>    add_column :users, :stripe_customer_id, :string, default: nil<br>  end<br>end</pre><h4>The credit card form</h4><p>Now we need a form to process the credit card details, but unfortunately up till now we haven’t needed a users_controller &amp; it’s associated view. So let’s create that now.</p><p>We’re also going to need the <a href="https://github.com/stripe/stripe-ruby">stripe gem</a>, so that we have easy access to the Stripe API from within the application (e.g. we can create a customer from within our controllers/models). So go ahead and add that to your gemfile .</p><p>The stripe gem needs to be able to consumer our publishable and secret keys (Which we have stored as environment variables), so let’s create config/initializers/stripe.rb</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7356b10e13114f2e92fae439bfc41114/href">https://medium.com/media/7356b10e13114f2e92fae439bfc41114/href</a></iframe><p>P.S. restart your server for the new initializer to kick in</p><p>Our new users_controller should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b56dc0c966c42d1ca6814653ab51466/href">https://medium.com/media/4b56dc0c966c42d1ca6814653ab51466/href</a></iframe><p>Then we need a form to add this info into, so stripe has something to process. I’ve decided to be lazy and plop this right onto the merchants/index page with everything else so let’s create a partial called merchants/_billing.haml.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/78df4f5da841e10d7592e73562d1f81f/href">https://medium.com/media/78df4f5da841e10d7592e73562d1f81f/href</a></iframe><p>Finally need to write a bit of javascript that will:</p><ol><li>Intercept the forms submit action</li><li>grab all the credit card data</li><li>Send it to stripe</li><li>Let stripe return a temporary token (a reference to the credit card)</li><li>Insert the token in a hidden field</li><li>Then perform the submit action of the form</li></ol><p>So let’s createassets/javascripts/verify_card.js</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1016cddf0ad60d34285b79ceddb600c6/href">https://medium.com/media/1016cddf0ad60d34285b79ceddb600c6/href</a></iframe><p>Ok let’s test it out by going to our root page and adding in some test credit card details, <a href="https://stripe.com/docs/testing">which Stripe’s awesome documentation provides for us</a>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SJu5qvuNh_nYkPFwMfOPhg.png" /><figcaption>Using a test card</figcaption></figure><p>Now when we hit submit, our JS will kick in and verify the credit card. Then it’ll return the stripe_temporary_token that our update action needs to create our user as a stripe customer!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/871/1*CKp_AsKec4AH5Y9qLGyg0w.png" /><figcaption>Successfully getting a token, and using it to create a customer in stripe!</figcaption></figure><p>Finally, let’s head over to the stripe dashboard again and verify that this user is registered on our account.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*wy5jx_odYYnJBE1WZUQlSQ.png" /><figcaption>SUCCESS!</figcaption></figure><p>AWESOME!</p><h3>Creating a charge</h3><p>Great now we’ve got users as customers and merchants as connected accounts. Let’s make sure that whenever a user buys a charge is created on stripe.</p><p>First let’s add a two fields to track the whether the payment has succeeded, so let’s run:</p><pre>rails g migration add_stripe_paid_field_to_transaction paid:boolean, stripe_charge:string</pre><p>But make sure to set default to false for the paid field.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/42198262b5359e2a11c6a50250404e0c/href">https://medium.com/media/42198262b5359e2a11c6a50250404e0c/href</a></iframe><p>Once you migrated this (and added these new params to our params.requirein our transcations_controller ), we’ll have a few fields we can use to track whether payment succeeded, based on the callback from the stripe charge event!</p><p>Now it’s time to create the model method needed to fire of a charge, and set our boolean depending on it’s success. So let’s head on over to models/transaction .</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a6137fafcc063d2604d8912aeb939a7e/href">https://medium.com/media/a6137fafcc063d2604d8912aeb939a7e/href</a></iframe><p>So this is a basic example of what a charge event should look like, but I’d strongly recommend taking a look at the <a href="https://stripe.com/docs/api#charges">Stripe Charge API reference</a>. Regardless we should be able to make a charge now. Let’s update our views to show this info:</p><p>views/transactions/show</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f53c94b98e2f1f79aa6ac89cdda555ab/href">https://medium.com/media/f53c94b98e2f1f79aa6ac89cdda555ab/href</a></iframe><p>views/transactions/index</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cf13a5d691312c744730b66006d480cb/href">https://medium.com/media/cf13a5d691312c744730b66006d480cb/href</a></iframe><p>Now let’s go ahead and buy something!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*q5pgTF731BlNM2dnUWsp7Q.gif" /><figcaption>if the callback succeeded we should have a charge ID &amp; and payment should be true!</figcaption></figure><p>Hopefully that succeeded, and you’ve now got a reference to the stripe charge, so let’s on over to our stripe dashboard to double check it.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KF7FSi1Guco7GEnzGsIG1Q.png" /><figcaption>WIN!</figcaption></figure><p>And there you have it, a successful charge in stripe from User, to Merchant, via the Connect Platform.</p><p>That’s it for this blog. In the final part of this series we’ll tackle:</p><ol><li>How to charge a platform fee on transactions</li><li>How to credit users, and split payments to cover those credited payments</li><li>General Cleanup of our little application</li></ol><p>Thanks for reading and let me know if you spot mistakes or errors!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9751c0e553f9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Stripe Connect & Rails — Part 1]]></title>
            <link>https://medium.com/@ThatGuyTinus/stripe-connect-rails-part-1-22ba7204725b?source=rss-7de91c0df26c------2</link>
            <guid isPermaLink="false">https://medium.com/p/22ba7204725b</guid>
            <category><![CDATA[stripe]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[online-payments]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Tinus Wagner]]></dc:creator>
            <pubDate>Sun, 28 May 2017 07:22:43 GMT</pubDate>
            <atom:updated>2017-06-11T06:34:58.146Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*m6pXBFDNitef-VSsgbWC2g.png" /></figure><h4>This is Part 3 of my series on integrating Stripe Connect into a ruby on rails application</h4><p><a href="https://medium.com/@ThatGuyTinus/stripe-connect-rails-part-2-9751c0e553f9"><em>Read part 2 here</em></a></p><p><a href="https://medium.com/@ThatGuyTinus/stripe-and-rails-part-3-63e22abde900"><em>Read part 3 here</em></a></p><p>I’ve been working on an application recently that needed to present users with a marketplace where they can act as both buyers and sellers of goods/services. The most daunting challenge for me was immediately how we’re going to handle payments, booking fees, discounts, and whatever else might be thrown at us when handling money.</p><p>More importantly, how do we roll this all up into a nice central system? To the rescue came <a href="https://stripe.com/connect">Stripe’s connect platform</a>. An all-in-one solution to handling marketplace style payments that flow from user to user, via a platform.</p><p>So I thought I’d do a bit of writing and try to explain how all the concepts and features could fit together in series of blogs. In this first post, I’ll dive into the concepts and requirements you’ll need to familiarise yourself with. Then from part two onwards, we’ll build a rails application that puts it all into practice!</p><p><a href="https://medium.com/@ThatGuyTinus/stripe-connect-rails-part-2-9751c0e553f9">If you’d like to just jump into the tutorial head over to part 2!</a></p><h4>Shoutout to the community!</h4><p>I honestly cannot praise the <a href="http://irc.lc/freenode/stripe">Stripe developer community</a>, and the impeccable <a href="https://stripe.com/docs/connect">Stripe documentation</a> enough. Get involved and you’ll find all the help you need.</p><h3>So let’s start, the requirements/features</h3><ol><li>Users should be able to verify their credit cards, and we should be able to identify them as unique customers from within Stripe</li><li>Hosts should be able to register their businesses in order to receive payments or process refunds</li><li>The platform should be able to charge a fee on each booking.</li><li>The platform should allow us to credit users on the platform</li></ol><h3>Setting up the platform</h3><p>So let’s get started and create a <a href="https://dashboard.stripe.com/register">Stripe</a> account. Once that’s good to go navigate to your settings, and head over to the Connect tab.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*qQV4klQatKXy3AqxiO44gA.png" /><figcaption>PEW</figcaption></figure><p>The first thing you’ll need to understand is the difference between what Stripe refers to as Standalone &amp; Managed Accounts:</p><h4>A <a href="https://stripe.com/docs/connect/connecting-to-accounts#standalone-accounts"><em>standalone</em></a> Stripe account is a normal Stripe account that is controlled by the account holder: your platform’s user.</h4><h4>By contrast, <a href="https://stripe.com/docs/connect/connecting-to-accounts#managed-accounts"><em>managed</em></a> accounts are fully controlled by the platform.</h4><p>After evaluating my needs, I decided to set Hosts up as standalone accounts.</p><h4>You’re probably most interested in Standalone Accounts if you:</h4><ul><li>Want to get started as quickly as possible. (Platforms that don’t manage accounts are much easier to set up and require far less custom code.)</li><li>Have users who are already existing Stripe users.</li><li>Live in a country that doesn’t support managed accounts yet.</li></ul><p><strong>Standalone Accounts</strong></p><p>Basically these are the account types that your <strong>Hosts</strong> will need to use to receive payments. And for this Stripe recommends using their <a href="https://stripe.com/docs/connect/reference">oAuth flow</a>. Just so we’re clear on what this might look like:</p><ol><li>As an already signed up user on our app, I want to connect my business to Stripe by either creating a new stripe account, or attaching an existing one.</li><li>Starting on a page at your site, the Host will click a button/link/something that will take them through to Stripe, passing along your platform’s client_id.</li><li>On Stripe’s website, the user will be prompted to connect or create their businesses Stripe account.</li><li>The user will then be redirected back to your site (your redirect_uri), passing along either an authorization code or an error (if the connection request was denied).</li><li>Your application then consumes this OAuth token information, and adds the needed data to their record.</li><li>Subsequent API requests can be made on behalf of the connected account using the previously mentioned credentials from the token.</li></ol><p>At the end of the day you should have a publishable_key associated with that host, which is it’s reference in Stripe to that users business.</p><p><strong>In Summary</strong></p><ul><li>we’ll have a unique ID for our platform (STRIPE_CONNECT_CLIENT_ID)</li><li>our users (sellers) will have a unique ID connected to the stripe account of their respective business (UID)</li><li>Our sellers will have a key attached to our Stripe account, that in combination with their UID, enables API requests (PUBLISHABLE_KEY)</li><li>our users (buyers) will have a customer ID (that references their saved credit card details internally), via a customer object that stripe gives us (we have indirect access to their credit cards, BUT WE DON’T STORE THEM, STRIPE DOES). (STRIPE_CUSTOMER_ID)</li><li>You’ll also have regularAPI keys for your application (STRIPE_PRIVATE_KEY)</li></ul><h3>Let’s get started</h3><h3>Adding Users</h3><p>So we need to get our user’s Credit Cards into the stripe system as <strong>customers. </strong>So have a look at <a href="https://stripe.com/docs/stripe.js/switching">stripe.js</a>, which has awesome documentation on grabbing user data out of a form, validating it via Stripe, and if successful, returning a reference to that credit card, which we can then use to create a customer object within Stripe.</p><p>But it’ll basically return a temporary token that looks somewhat like this:</p><p>“tok_0XXXXXXX0XXXxxxxXXxX0xX0”</p><p>We can use this token to create a single once-off charge, or alternatively we can consume this token to create our users in stripe as customers. Once this is done Stripe will return a stripe_customer_id which we can use in the future for far more than just a charge.</p><p>It’ll look something like this:</p><p>stripe_customer_id: “cus_X1XXXxXxXxX1Xx”</p><p>Keep in mind that this is <strong>not a credit card</strong>, this is a reference to a customer object, in Stripe’s custody, that in combination with our platform ID, we can use to request that a charge be made by Stripe.</p><h3>Adding Hosts</h3><p>For this I’d recommend making use of the <a href="https://github.com/isaacsanders/omniauth-stripe-connect">omniauth-stripe-connect</a> gem. If you use Devise for your authentication needs, you’ll have found the perfect match.</p><p>Now this portion will require you to head over to the settings within the Connect tab in Stripe, and to set a redirect_uri for your environments. Basically once a user hits the omniauth process, and successfully registers their business, Stripe will use this URI to pass back the merchant object, which contains a whole host of save-able account details.</p><p>The most important part here is the Merchants UID, because it is critical to creating charges, but trust me, you can pull a lot of information out of the returned object.<a href="https://stripe.com/docs/api#create_account"> Check out the API reference</a>.</p><h3><strong>Creating a charge</strong></h3><p>In essence we now have everything we need to make a charge.</p><ul><li>A customer to charge</li><li>A merchant to credit</li><li>A reference to the marketplace or platform (which is dealt with separately, but important if you decide to charge a platform fee)</li></ul><p>But what else can we string into a charge? What options do we have? <a href="https://stripe.com/docs/api#create_charge">The Stripe API gives you plenty of options.</a></p><p>But here’s an example of what that could look like, with a bit of light error handling:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/5d3cf2ea917ad940a7382501908f4b0b/href">https://medium.com/media/5d3cf2ea917ad940a7382501908f4b0b/href</a></iframe><p>So hopefully this post has clarified some of the concepts you’ll need to become familiar with while implementing the Connect Platform. In Part 2 we’ll create a little application for those of you who prefer hands on learning ;)</p><p>Thanks for reading and let me know if you spot any mistakes or oddities.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=22ba7204725b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails To Anything — Integrating Zapier via Webhooks]]></title>
            <link>https://medium.com/@ThatGuyTinus/rails-to-anything-integrating-zapier-via-webhooks-3e51a8f6a54f?source=rss-7de91c0df26c------2</link>
            <guid isPermaLink="false">https://medium.com/p/3e51a8f6a54f</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Tinus Wagner]]></dc:creator>
            <pubDate>Wed, 19 Apr 2017 10:19:26 GMT</pubDate>
            <atom:updated>2017-04-19T10:19:26.608Z</atom:updated>
            <content:encoded><![CDATA[<p>Over the last few days I’ve had a client introduce me to a pretty crispy service called <a href="https://zapier.com/">Zapier</a>. If you’ve never heard of it, it’s basically an automation tool for tasks between apps.</p><p>Naturally it also supports webhooks which in the bigger scheme of things is pretty cool. Instead of having to integrate a whole handful of API’s for whatever services my client would like to use. I can create one POST request to Zapier, and give the client the power to do whatever he/she desires with that data. Wether it be scheduling a slack notification when an invoice is created, adding a newly registered user to a google doc, or subscribing a user to a mailchimp list after they’ve created X amount of content.</p><h3>Before we get started</h3><p>Pretty much every service Zapier integrates with already has some sort of public API you can use, I’m aware of that. But if you need to integrate with many in a small timeframe and don’t want to get bogged down with collecting a small bag full of api keys, authorizations, and tests, for multiple services, then this might be helpful.</p><p>It’s a lot more fun letting the customer know that the data is in zapier and that they can now pretty much do whatever they want with it. And as you’ll see in this example, it’s pretty simple.</p><h3>Setting this up in a Rails application</h3><p>So I opted to use a pretty amazing gem called httParty, which “makes http fun again” according to the authors. In all seriousness it’s a great wrapper for <a href="https://www.w3schools.com/tags/ref_httpmethods.asp">all things GET, POST &amp; PUT</a>. So let’s get started.</p><p><a href="https://github.com/jnunemaker/httparty">Head over to their github page and give the documentation a quick read</a>, then jump into the console and run:</p><p>gem install httparty</p><h3>Onto our Zapier Service</h3><p>Let’s keep things nice and tidy, let’s set up a service. Head on over to your services directory and create a new folder for <strong>zapier</strong>. We’re going to need a few things:</p><ol><li>A <strong>base.rb</strong> file that can deal with initialising attributes &amp; resources, dealing with the base response from zapier, and in this case, doing a light bit of error handling.</li><li>a File for each individual zap you’d like to create, along with whatever params and functions you’d like to cram into it.</li><li>Some way of saving the url hook provided by zapier. Could be a file in config/initializers, or you could use the brilliant gem <a href="https://github.com/bkeepers/dotenv">dotenv</a>.</li></ol><figure><img alt="" src="https://cdn-images-1.medium.com/max/201/1*gRToPqEeRz_Qxxsqt40UXw.png" /><figcaption>I’ve named my Zaps after the model the inherit from, but if you have multiple events firing off from the same model/controller, it’s probably better to name them specific to their purpose (e.g. new_place_created.rb)</figcaption></figure><p>So let’s get started on our base.rb file.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/559c75ea5ec558e22b79985c4136e9e4/href">https://medium.com/media/559c75ea5ec558e22b79985c4136e9e4/href</a></iframe><p>We’re doing a couple of things here:</p><ul><li>initialising httParty</li><li>setting a few attribute accessor &amp; reader methods to manipulate the request and response</li><li>Initialising the resource we’ll be using as a source for the POST request</li><li>Laying out the format the request will take</li><li>Saving the response code returned from Zapier upon a successful (200)</li><li>A little sanity check test to catch oddities &amp; failures</li></ul><p><strong>Keep in mind that every file we create from here on out will inherit from base.rb</strong></p><p><strong>Zap Example:<br></strong>In the example I’ve created, I have zap’s that are firing off when specific model methods are triggered.</p><p>Whenever a user creates a space, I want to send a few pieces of data to Zapier.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/232fe45b1fcb5e220a78bc362d8acb14/href">https://medium.com/media/232fe45b1fcb5e220a78bc362d8acb14/href</a></iframe><ol><li>define the POST request in our call_operation which executes when the service is fired. The first argument here being the hook url that is supplied when creating a new zap, and the second being the parameters we’d like it to send.</li><li>We define which parameters the POST request will…POST. You can format your params as either JSON as I’ve done, or XML.</li></ol><h3>And that’s about it, rinse and repeat</h3><p>All you need now is an action to fire the hook with! Whether that be a hook somewhere into the <a href="http://api.rubyonrails.org/classes/ActiveRecord/Callbacks.html">callback_order</a> when creating a record, or as part of a method somewhere in your model, or both as I’ve done!</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/26188351d50e17e22058e84e0991b61b/href">https://medium.com/media/26188351d50e17e22058e84e0991b61b/href</a></iframe><h3>…How do I know if it’s working?</h3><p>Jump back to Zapier and give it a test of course. If the Zap receives the post request successfully, you’ll be able to view the sent data as well.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C7Ya7BawMzyMpV523HMq1Q.png" /><figcaption>A successful JSON POST request with the 3 params I included</figcaption></figure><p>And that’s it. Enjoy.</p><h3><strong>Tip</strong></h3><ul><li>if you’d like to send the same parameters to more than one Zap url at a time, you totally can by stringing various webook urls together. <a href="https://zapier.com/help/webhooks/#triggering-multiple-webhooks-at-once">Zapier will still trigger each individual request.</a></li></ul><p>Thanks for reading and let me know if I got anything wrong!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3e51a8f6a54f" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>