<?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 Adam Mazur on Medium]]></title>
        <description><![CDATA[Stories by Adam Mazur on Medium]]></description>
        <link>https://medium.com/@mazik.wyry?source=rss-ec7d7f05aee3------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*J8yYBT173KylThye.</url>
            <title>Stories by Adam Mazur on Medium</title>
            <link>https://medium.com/@mazik.wyry?source=rss-ec7d7f05aee3------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 21 Nov 2026 07:09:59 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@mazik.wyry/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[5 Best Practices to Accelerate Code Review]]></title>
            <link>https://medium.com/@mazik.wyry/5-best-practices-to-accelerate-code-review-4a90bf7581f8?source=rss-ec7d7f05aee3------2</link>
            <guid isPermaLink="false">https://medium.com/p/4a90bf7581f8</guid>
            <category><![CDATA[tech-leadership]]></category>
            <category><![CDATA[pull-request]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[pull-request-reviews]]></category>
            <category><![CDATA[code-review]]></category>
            <dc:creator><![CDATA[Adam Mazur]]></dc:creator>
            <pubDate>Tue, 13 Feb 2024 12:47:52 GMT</pubDate>
            <atom:updated>2024-02-13T12:47:52.593Z</atom:updated>
            <content:encoded><![CDATA[<p><em>This article was originally posted on </em><a href="https://www.globalapptesting.com/engineering/5-best-practices-to-accelerate-code-review#1-traffic-lights"><em>GAT Engineering</em></a><em> blog.</em></p><p>I ❤️ doing code reviews. Really! Reviewing code allows me to stay up-to-date with the system state, learn from others, ensure quality and share my knowledge and experience. Recently, my team has grown and some less experienced engineers have joined. It turned out they found my comments in code reviews a great way to learn, but on the other hand, a bit overwhelming and blocking. Sometimes, their pull requests hang in code reviews unnecessarily and frustratingly long. I want to share some practices I started experimenting with that have helped my teammates merge pull requests quicker, reduce frustration, and upskill.</p><h3>The story</h3><p>Before my team grew, I predominantly worked with very experienced engineers that I’d known for years. I didn’t have to think about how they would react to my reviews — they somehow knew intuitively which comments they were supposed to apply, which were “nice-to-haves,” where we needed a further discussion and what the overall review result was. Our system worked magically and effortlessly.</p><p>After younger, eager-to-learn developers joined, it turned out that they tended to apply all of the suggested changes. When I asked for feedback about my code review, one of them said: “When I see a suggestion from a much more experienced dev, I assume that I should apply it.” That was a game-changer for me. That moment I recalled the last Pull Request where I left ~50 comments and just imagined how frustrating it must have been for my new teammate. OMG.</p><p>After discussing the topic, here are the best practices that we came up with:</p><h3>#1: Traffic lights</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*kP1YB2cpOsw6tTiW.jpeg" /></figure><p>I categorized code review comments by the importance and actions that I would expect to be taken, resulting in three categories:</p><ol><li><strong>Blockers</strong> — things that block me from approving a Pull Request (e.g. bad design, rule break, code smell, security issue, missing spec)</li><li><strong>Warnings</strong> — things that worry me or I don’t understand (e.g. I don’t get the context, need to make sure that something was checked)</li><li><strong>Improvements</strong> — mostly small refactorings, cleanups, syntax sugars (many people, especially from the open-source community, would call them “nits”)</li></ol><h3>It reminded me of traffic lights, so I assigned colours and emojis to them: 🍎Blockers, 🍍Warnings and 🍏 Improvements.</h3><p><em>Why apples? Easy to use in GitLab comments — just type </em><em>:apple and you get those three in suggestions.</em></p><p>I paired with my teammate again and explained actions that I would expect in response to a certain type of comment:</p><ul><li>🍎 Blockers — we need to change this,</li><li>🍍 Warnings — let’s check and discuss and the discussion should resolve into Blocker or Improvement (or just no action when everything is fine),</li><li>🍏 Improvements — we can skip or apply later.</li></ul><p>While for blockers and improvements, it is quite clear and binary, reactions to warnings can vary case-by-case. For example, when you ask a question, the next steps depend on the answer.</p><blockquote>Pro-tip: If there are limited possible answers to your question, you can proactively share your expectations for each of them.</blockquote><blockquote>Example: Is it A or B? If A then we need to use XYZ (blocker), otherwise we can stick to your solution (no action).</blockquote><blockquote>We just reduced one feedback loop. Yey!</blockquote><p>Warnings could also be calls to discuss something with a ticket/story owner (e.g. product manager or designer). Then we need to wait for the decision that would resolve to something else.</p><p>It’s hard to list all cases here, but I hope that the general idea is quite clear.</p><p>When I explained this to my new colleague, he said: “Hey, this is exactly what I need from you!”</p><p>Then I realized that it could also be helpful for my more experienced colleagues. Now they can see what I expect, they would most likely not remain silent on something that I see as a blocker or might skip something with a good conscience.</p><p>Here are some examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*UXtN09LXhb2NmQY3.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*jBsp6S_DayMtpD1V.jpg" /></figure><p>How does it speed up the code review feedback loop? As a code author:</p><ul><li>I don’t have to think about what the reviewer expects</li><li>I don’t have to apply all the suggestions</li><li>I can start resolving comments from the most important (blocking) ones</li></ul><p>Low effort, high impact.</p><h3>#2: Review summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1022/1*fHUV0WERif2f8LO71156Tw.jpeg" /></figure><p>In the feedback that I received from my teammate, he shared how useful my review summaries have been. This is something that I was doing from time to time, especially when leaving quite a lot of comments. I don’t have any strict template for such a summary, but I try to always include:</p><ul><li>What is my overall perception of the solution?</li><li>What are my expectations for the next steps?</li></ul><p>I usually use the former for praising, but when I really don’t like the solution or the author missed the point — here is the best place to give that feedback.</p><p>In my expectations, I try to express <strong>what needs to be done to move us closer to approval</strong>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*mfsBcKMfsNO4eDGd.jpg" /></figure><p>Such a summary read after all comments/suggestions should give the author a clear image of what I think about the solution and what should be the next steps. Of course, this is not something that I leave in every review. From my experience, it’s mostly useful for bigger pull requests, when leaving many comments.</p><h3>#3: “I trust you” approval</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*9NSGVJpg-dNFLWSb.jpeg" /></figure><p>This is a dead simple practice: <strong>Approve pull request when the only suggestions you left were “Improvements”</strong> In other words when all warnings are resolved and there are no blockers, nothing is stopping me from approving.</p><p>If I waited for all the “Improvements” to be implemented, I would be adding a feedback loop.</p><p>I usually don’t get back to the pull request after approval and don’t check which suggestions were applied. I just <strong>trust</strong> my teammates that they will consider effort vs. impact and make the right choice. Even if not — these are just improvements that can be done later.</p><p>Before you start practising this, discuss this with your team to avoid confusion when they receive 10 comments and approval. Depending on your team and project, you may also consider setting explicit expectations. Example:</p><blockquote><em>When you skip an improvement comment, always create a ticket and put it in the backlog with a </em><em>improvement label</em></blockquote><p>This removes another review iteration.</p><h3>#4: Quick call?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*Ynw4pzjl60OFlcpf.jpeg" /></figure><p>Async, long discussions in Pull Request comments can take days. Sometimes when you see that after 10 comments in a thread or three days of ping-pong (when usually it takes two days to merge), you are still far from an agreement or are talking about two completely different things, it can be quicker to jump on a call, share your screen and resolve it that way. Just don’t forget to leave a call summary in a thread.</p><p>At Global App Testing, we use Slack huddles for such cases. I wish we could have “GitLab huddles” that brings all the discussion participants into one audio room with just one click in the thread. If you know anyone at GitLab, please send them this article.</p><p>That could save even more iterations. Oh, if only I would do this always…</p><h3>#5: Manual nudges</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*eUfutpPmLYWQ39Y8.jpeg" /></figure><p>We tried some plugins and integrations that were automatically pinging us with pending Pull Requests waiting for reviews. While it was working for a while, pings quickly became ignored. :(</p><p>We decided on having a dedicated Slack channel where we started posting manual requests for reviews; it continues to work surprisingly well and has sparked a lot of creativity on how to incentivize people to check pull requests. Just look at these:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/247/0*iw1PWhIi9J57J1mA.jpg" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/416/0*0MhOS1GmWmI6TZzN.jpg" /></figure><p>We use the same channel to ask about the next iteration after we apply all the fixes (which is harder to automate).</p><p>I observed that it’s easier to ignore robots than people (especially when you see the effort they put into creating a meme). This reduced time to the first reaction after making the pull request ready for (re)review.</p><h3>BONUS</h3><p>If you’re still reading, I will leave you with two more practices.</p><p>When you have a debate about different solutions or approaches, it’s good to communicate how strong your opinion is and be clear about who you expect to make the final decision.</p><p>If you state that you have a strong opinion, the author of the Pull Request will know that they either have to provide a strong argument or ask a third person to step in. It’s less likely that they will skip your opinion. As a PR author, I sometimes ask the reviewer how strong their opinion is and find that it usually helps resolve the discussion. I imagine this is because such a question causes a reflection and cools down emotions.</p><p>When it comes to making the final decision, it depends on your role. If you are a tech lead or a code owner, the decision can be yours by default, but you can always explicitly delegate it to the PR author (when you think that a bad decision won’t be that harmful). When the code author is your peer and you can’t agree, it’s always a good idea to ask a third person — ideally someone decisive.</p><h3>Summary</h3><p>The number of feedback loops is especially important in a remote/async environment, whereas the author of the code, you must sometimes wait hours for the next review iteration. Four iterations might mean four days (maybe an extreme, but just imagine a remote cross-timezone environment). <strong>(In the office you can probably just sit together and go through the code — applying changes on the fly.)</strong></p><p>I’ve shared a few practices that can help you significantly reduce the number of feedback loops and shorten them, so you can improve your delivery time. This article can be summarized by four main points:</p><ul><li>Share overall perception</li><li>Be explicit about your expectations</li><li>Trust others</li><li>Adjust communication channels</li></ul><p>By implementing these practices, you can shave off at least one iteration, which could sometimes save a whole day!</p><p>I’m curious to hear about your practices related to the code review process.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4a90bf7581f8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[React for Rubyists: Simple React/Redux todo app written in Ruby]]></title>
            <link>https://medium.com/@mazik.wyry/react-for-rubyists-simple-react-redux-todo-app-written-in-ruby-33b588932bb1?source=rss-ec7d7f05aee3------2</link>
            <guid isPermaLink="false">https://medium.com/p/33b588932bb1</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[react]]></category>
            <dc:creator><![CDATA[Adam Mazur]]></dc:creator>
            <pubDate>Fri, 27 Apr 2018 11:51:44 GMT</pubDate>
            <atom:updated>2018-04-27T11:51:44.249Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>This post is to help Ruby users understand ideas behind React and Redux.</strong></p><h3><strong>Why?</strong></h3><p>Everyone that knows me is aware that I don’t like Javascript. Another well-known thing is that I love Ruby. When I discovered React I found it a great solution for nowadays client-side applications. The idea behind component-based approach allows developer to isolate and atomise elements of the app. The biggest downside of React (apart of it is written in JS) is that it introduces JSX. This in not something that we were fighting for. For the last few years we have been trying to find the best way to separate HTML from JS and CSS, to separate business logic layer from presentation layer and now JSX combines everything together.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/153cc3bdaae54b4defb9678bed52c971/href">https://medium.com/media/153cc3bdaae54b4defb9678bed52c971/href</a></iframe><p>So the idea of React is great, but the solution isn’t perfect. I was wondering why we can’t combine Ruby which is smart and elegant with React? One of the reason why we can do that is that React is object-oriented. You create a template of a component (class) and then you create many instances passing some parameters. JS is not for OOP. In Ruby everything is an object, though. It seems like a perfect match.</p><h3>How you can run Ruby in the browser?</h3><p>Directly you can’t. The same way as ES2016, ES2017, CoffeeScript and TypeScript. We use all of them. Why? Just because most of us feel under the skin that JS syntax isn’t perfect. So we have transpilers like Babel to compile from JS to JS. Ruby has it’s own compiler — <a href="http://opalrb.org/">Opal</a>.</p><blockquote>Opal is a Ruby to JavaScript source-to-source compiler. <br>It comes packed with the Ruby corelib you know and love. <br>It is both fast as a runtime and small in its footprint. — Opal creators</blockquote><p>Ok, so we get rid of JS. Now we have to face the problem of JSX. Here the <a href="http://ruby-hyperloop.io/">HyperLoop</a> with HyperReact comes!</p><blockquote>HyperReact is a wrapper for the React.js library for creating user interfaces. HyperReact provides all the goodness of React combined with the expressiveness of the Ruby language.</blockquote><p>This is exactly what we need. HyperReact provides a very simple DSL for creating components classes. Let’s have a look at the example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bc738963966401018f1cae8ce55f4416/href">https://medium.com/media/bc738963966401018f1cae8ce55f4416/href</a></iframe><p>Isn’t it more elegant? Right, we got all the tools. Let’s build something.</p><h3>Simple Todo App</h3><p>That will be a very simple and limited version of the Todo app, cos it will only allow you to list tasks and add new. This is because I only want to show how it works.</p><p><strong>Task Class (ToDo)</strong></p><p>First, let’s create very simple class for representing a single task (todo). Nothing special.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/117e00f234cef24e6a8e7f34d6637322/href">https://medium.com/media/117e00f234cef24e6a8e7f34d6637322/href</a></iframe><p><strong>Task Component</strong></p><p>What I like in React is that you can focus on a single component in isolation. We need display single task, so no matter in what context we will use the task, it should look and work the same way (unless we want it).</p><p>I’m a fan of bottom-up approach so let’s start from the single task component.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6117f22306c178f19933c6321fc35c53/href">https://medium.com/media/6117f22306c178f19933c6321fc35c53/href</a></iframe><p>Very simple component for very simple purpose. As you can see here we pass todo as a parameter and it is an Object which matches ruby object.</p><p><strong>Task List Component</strong></p><p>Now using the component above we can create a component that lists all the tasks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4a2f069ec88a14976ec7bd860b92c4d4/href">https://medium.com/media/4a2f069ec88a14976ec7bd860b92c4d4/href</a></iframe><p>You can think of it as about microservices. They have a single responsibility and utilises other microservices.</p><p><strong>Form Component</strong></p><p>The first feature is ready. Now let’s add a form that will allow to input new tasks.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/83e1b31a063581d8d256e4322dc422cf/href">https://medium.com/media/83e1b31a063581d8d256e4322dc422cf/href</a></iframe><p>You can spot some new elements here. define_state lets us define internal state of the component. In fact it’s an instance variable — nothing less, nothing more. Basing on the state and how it changes React builds VirtualDOM.</p><p>We don’t implement `add_todo` method here. Instead we pass the method as a parameter. This is to separate the presentation layer from business logic. Form component is a place for inputs and buttons. Presentation elements only.</p><p><strong>ToDo Box</strong></p><p>Right, we have all the components. All created above are dump-components. They are don’t know much how the whole app works. They are isolated and simple. Now we need one smart-component a.k.a. container. This component has some logic and create instances of dump-components. It is a common practice to call them boxes. Here is our ToDoBox :</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4e539ef10ada7b1abcc3702e390a3349/href">https://medium.com/media/4e539ef10ada7b1abcc3702e390a3349/href</a></iframe><p>You can see that this is still very simple and elegant. We have a render block that uses dump-components and add_todo method that implements adding new task to the list. To explain the implementation of add_todo we need to stop here and talk a little bit about client-side application state.</p><p><strong>Application state</strong></p><p>It’s pretty straightforward that application state is an data set that identifies in which state the application is <strong>at the moment</strong>. We don’t have it in Rails apps, cos they are stateless. As client-side applications started to grow managing the state of the app has became a big issue. One of the most popular solution today is Redux which works great with React.</p><p>Redux comes with a very simple model. We have one state for the whole app which is immutable (read-only). We can change the state only by making some actions/events (f.e. sending a form, clicking a button).</p><p>Here is a great animation that shows the flow of Redux:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*UxK2YBngoT3p08RvlrGXEw.png" /><figcaption>Redux flow</figcaption></figure><p>We have following elements:</p><ul><li><strong>Store </strong>— home for the current state, Reduces and Dispatcher</li><li><strong>Reducer </strong>— which produces new state of the app basing on actual state and the action the came from the Dispatcher</li><li><strong>Action </strong>— operation that should be done on actual state (f.e. add_todo), is based on an app event (f.e. button click, form submit)</li><li><strong>Dispatcher </strong>— takes the action and pass it to the reducer. It works like a Rails dispatcher.</li></ul><p>Here is the simple and full implementation of Redux store for our application:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3221c87fa7926d09ba65ac360380627d/href">https://medium.com/media/3221c87fa7926d09ba65ac360380627d/href</a></iframe><p>The most important thing here is the reducer method which is the heart of the store. It defines how the state should change if the store will receive add_todo action.</p><p>Let’s get back to our ToDoBox and the implementation of `add_todo` method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/663212a13cda5fbb5794a038be00c88a/href">https://medium.com/media/663212a13cda5fbb5794a038be00c88a/href</a></iframe><p>We tell the store to dispatch action add_todo with id and body as additional parameters (which reducer implementation knows how to use).</p><p>Once reducer will receive the action, it will <strong>produce </strong>new state (not change, co remember it’s immutable) and React will do the job and refresh the view. User will see his newly created task on the list.</p><p><strong>Running the app</strong></p><p>We’ve got all the components and the store. Let’s run our application:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c6aa7ab0376335d59340e27b67c3fd76/href">https://medium.com/media/c6aa7ab0376335d59340e27b67c3fd76/href</a></iframe><p>After requiring stuff needed we create store object and initialise it with an empty array. Then we create a lambda function that renders our smart-component. On document ready event(thanks to elegant Opal JQuery DSL) we subscribe for store changes, so store will re-render (using React magic tricks with VirtualDOM) our component on changes. Finally we call the render function to initialise the view.</p><h3>Summary</h3><p>We created a very simple and limited todo app to show basic ideas behind React and Redux using Ruby and its Opal and HyperLoop libraries. If you want to see the application in action and get into the details of how to run it in the browser please <a href="https://github.com/mazikwyry/todo_react_in_ruby">see the full code on Github.</a> You can fork it and write more features. Thank you for your time and hope to see you soon!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/408/1*EkPYKoA3ZvIEVVjJ2TNxaw.png" /><figcaption>Our app up and running</figcaption></figure><h3>Further reading</h3><ul><li><a href="http://ruby-hyperloop.io/">http://ruby-hyperloop.io/</a></li><li><a href="http://opalrb.org/">http://opalrb.org/</a></li><li><a href="http://voltframework.com/">http://voltframework.com/</a></li><li><a href="http://redux.js.org/">http://redux.js.org/</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=33b588932bb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails 5 API + JWT setup in minutes (using Devise)]]></title>
            <link>https://medium.com/@mazik.wyry/rails-5-api-jwt-setup-in-minutes-using-devise-71670fd4ed03?source=rss-ec7d7f05aee3------2</link>
            <guid isPermaLink="false">https://medium.com/p/71670fd4ed03</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[jwt]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[rails-5]]></category>
            <dc:creator><![CDATA[Adam Mazur]]></dc:creator>
            <pubDate>Wed, 14 Feb 2018 11:31:07 GMT</pubDate>
            <atom:updated>2018-02-14T11:31:07.097Z</atom:updated>
            <content:encoded><![CDATA[<p>Rails 5 is a great choice for your new API application. It has build-in api mode that has everything you need without the unnecessary “full stack” stuff. In this article I will show you how to setup your new Rails 5 API app with JWT (JSON Web Token) authentication.</p><h3>Step 1 — Rails in api mode</h3><p>Assuming you have Ruby and RubyGems already installed <em>(if not, I recommend great step-by-step guide on </em><a href="http://installrails.com/"><em>http://installrails.com/</em></a><em>)</em> just create new Rails project using new api option:</p><pre>$ rails new my_api --api</pre><p>With Rails 5 it is that simple! I won’t get into details how it really works. Just trust me that it’s a perfectly suited for your API-only application. You can read more about it in <a href="http://edgeguides.rubyonrails.org/api_app.html">Rails guides</a>.</p><h3>Step 2— JWT authentication</h3><p><a href="https://jwt.io/introduction/">JSON Web Token</a> is a great solution for user authentication. It‘s a well documented standard that has many implementation across almost all popular programming languages including Ruby.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/393/1*LVpAcf7V4v_CUF_shr_8Mg.png" /></figure><p>We will use <a href="https://github.com/waiting-for-dev/devise-jwt">devise-jwt</a> gem which is a “is a <a href="https://github.com/plataformatec/devise">devise</a> extension that uses JWT tokens for user authentication.”. Great job done by the author let us use JWT with the well known Rails authentication engine. When I was first implementing JWT in my application I was wondering whether devise, which is designed to use in full-stack Rails apps, is a good choice for API-only mode, but I gave it a go and after a few small tweaks it works and does the job.</p><p>Let’s see how to integrate it! Start with adding gem to your Gemfile (remember to checkout for the newest available version and specify it in Gemfile):</p><pre>gem &#39;devise-jwt&#39;</pre><p>Then we need to install devise as usual. If you not familiar with that gem or don’t remember how to do it checkout <a href="https://github.com/plataformatec/devise#getting-started">these instructions</a>. Basically what you need for now is to run the devise:install script and generate a User model. I recommend reviewing migration file that devise’s model generator creates and make sure you will get only fields you need.</p><p>Assuming you have you User model ready it’s time to provide some JWT specific configuration. We need to enable the extension in the model and it should look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c45f83514004b974502e5053311d67ca/href">https://medium.com/media/c45f83514004b974502e5053311d67ca/href</a></iframe><p>Now we need to setup JWT Revocation Strategies. It’s an advanced topic and if you are interesting I highly recommend reading <a href="http://waiting-for-dev.github.io/blog/2017/01/23/stand_up_for_jwt_revocation/">this</a> article by the author of the gem. All you need is to create blacklist model and migration:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0b7e0d6c61511a3743670ca462f3b2a5/href">https://medium.com/media/0b7e0d6c61511a3743670ca462f3b2a5/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/633cbc5f841f7f6d100bbcbc01bc5704/href">https://medium.com/media/633cbc5f841f7f6d100bbcbc01bc5704/href</a></iframe><p>Last part is to place JWT configuration in config/initializers/devise.rb</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7e1b7fbc5cf773d816f3d903b8830546/href">https://medium.com/media/7e1b7fbc5cf773d816f3d903b8830546/href</a></iframe><p>As you can see here we will have /login and /logout endpoints. You need to generate secret key yourself by running rake secret and place it in your environmental variables (<a href="https://github.com/bkeepers/dotenv">dotenv</a> gem makes it super easy). I also set the token expiration time to 1 day, cos the default time too short (few minutes).</p><p>While we are here let’s tell devise we will not use navigational formats by adding the following line to the same file:</p><pre>config.navigational_formats = []</pre><p>It will prevent devise from using flash messages which are not present in Rails api mode.</p><h3>Step 3 — Login/logout endpoints</h3><p>If you don’t need to do extra stuff on login/logout you even don’t have to override default Devise controller actions. All we need to do is to tell devise to speak with us using json format. This is the simplest solution I found:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/afc4bdf950facdfabaeab0e5d99d0484/href">https://medium.com/media/afc4bdf950facdfabaeab0e5d99d0484/href</a></iframe><p>After you place that file in app/controllers we need to set routes:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6786f1ab473d64224599ca4ab862ea87/href">https://medium.com/media/6786f1ab473d64224599ca4ab862ea87/href</a></iframe><p>As you can see we configure custom paths for our endpoints. If you are ok with default Devise paths ( users/sign_in , users/sign_out , users/sing_up ) just remove path and patch_names keys.</p><h3>Step 4— Registration</h3><p>For sign-up endpoint we will override Devise controller action with</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6f454adc6f9e63f61a8d30c5bb7f81ea/href">https://medium.com/media/6f454adc6f9e63f61a8d30c5bb7f81ea/href</a></iframe><p>The main reason for that is that on registration you usually do things like sending emails or tracking, so sooner or later you will have to write you own action. You may notice that we use a render_resource method which is not part of Devise API. It’s a custom method that I use for rendering resources (it’s not only for User resource). You can place it in app/controllers/application_controller.rb</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/14490f6b009cec87c17abf5545f059c4/href">https://medium.com/media/14490f6b009cec87c17abf5545f059c4/href</a></iframe><h3>Step 5— Request Specs</h3><p>Specs are the easiest way to make sure your API works as expected. In real world it’s better to write specs first, but for the blog post we will finish with that.</p><p>We will write some request specs. Why not controller specs? Because they don’t test the whole stack. They only create an instance of the controller class and fire the action method. They are useful if you have legacy code and want to refactor fat controllers. Otherwise I recommend using request specs which makes actual request and you test only the output (and critical side effects if needed). Using request spec also allows you to use <a href="http://watchdocs.io/">Watchdocs</a> which can generate your API documentation and helps you keep it up-to-date.</p><p>I will provide you with example specs in RSpec, just to give you an idea how those specs could look like.</p><p>First spec is for authentication endpoints and in addition for response status it also tests for JWT token presence and validity.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cee4e9d79cbecb651416b3c790810df8/href">https://medium.com/media/cee4e9d79cbecb651416b3c790810df8/href</a></iframe><p>The second spec is for registration endpoint:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4aea9c2709c939fd028652449a20b757/href">https://medium.com/media/4aea9c2709c939fd028652449a20b757/href</a></iframe><h3>Step 6— Build your app</h3><p>Now when you have authentication you can start building your API. In every controller that should be available only for authenticated users use a standard Devise’s</p><pre>before_action :authenticate_user!</pre><p>and you are at home!</p><h3>Conclusion</h3><p>I’ve just shown you how to start with Rails 5 in API mode and how to configure it to work with JWT using our best friend — Devise. This is of course a basic configuration, but it will work for most of the cases. For further reading on topics I mentioned here I recommend:</p><ul><li><a href="https://github.com/waiting-for-dev/devise-jwt">devise_jwt gem documentation</a></li><li><a href="https://relishapp.com/rspec/rspec-rails/docs/request-specs/request-spec">RSpec request spec documentation</a></li><li><a href="https://jwt.io/introduction/">Introduction to JSON Web Tokens</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=71670fd4ed03" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>