<?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 Diego Leite on Medium]]></title>
        <description><![CDATA[Stories by Diego Leite on Medium]]></description>
        <link>https://medium.com/@diegomelo_92702?source=rss-73f118f83f23------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*096X-f6f0zV1gYuJsq62bA.jpeg</url>
            <title>Stories by Diego Leite on Medium</title>
            <link>https://medium.com/@diegomelo_92702?source=rss-73f118f83f23------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sun, 22 Nov 2026 09:02:32 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@diegomelo_92702/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[Designing Scalable Applications from scratch]]></title>
            <link>https://medium.com/@diegomelo_92702/designing-scalable-applications-from-scratch-c4062396cecb?source=rss-73f118f83f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/c4062396cecb</guid>
            <category><![CDATA[scalability]]></category>
            <category><![CDATA[scaling]]></category>
            <category><![CDATA[load-balancing]]></category>
            <category><![CDATA[horizontal-scaling]]></category>
            <category><![CDATA[scalable-applications]]></category>
            <dc:creator><![CDATA[Diego Leite]]></dc:creator>
            <pubDate>Thu, 07 Sep 2023 11:19:54 GMT</pubDate>
            <atom:updated>2023-09-07T11:19:54.220Z</atom:updated>
            <content:encoded><![CDATA[<p>In this article, I will explain a little bit about Scalable Applications and what you need to know to implement this idea on your project.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Guar0NSFJuI9nAvaROpHqg.png" /></figure><p>I will start using an example of a real-life Application like a voting Application that can receive tons of requests per minute, so let’s think about the heavier part of the application that all people of the Country can access simultaneously we could use a <strong>SPA (Single Page Application)</strong> for the front-end and an API back-end.</p><h3>Single Page Application</h3><p>Let’s talk about <strong>SPA</strong> or <strong>Single Page Application</strong>, The usage of this kind of solution can help with the costs because you will need only an <strong>NGINX</strong> or <strong>Apache Web Server </strong>serving static files. However, it has some particularities that you need to bear in mind, for example, you will face some <strong>SEO (Search Engine Optimization)</strong>problems when you use this type of solution, because, it is an Application that runs only on the <strong>client side (Browser) </strong>and some of the crawlers are based in analyzing HTML rendered via back-end which doesn’t happen on SPAs given that the responsibility of rendering the HTML is on the client Browser.</p><p>Having said this, in our case, we will use an SPA for the screen that will receive all the users simultaneously as in this case we don’t need to care about the <strong>SEO</strong>.</p><h3>Frontend</h3><p>The main idea of this front end is to have only a static voting page that doesn’t have any session control or authentication just to make it as simple as possible to understand, then, as we talked about before, it is a SPA which is responsible to show the characters (via an API call) and to send the information about the selected character to the back end side.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*42slEcdBeD1jzjkben51wg.png" /></figure><p>Also, let’s imagine an endpoint (<strong>POST </strong><em>/api/votes</em>) that this front end is using for sending the data of the selected character when the users choose one and the VOTE button is clicked.</p><h3>API</h3><p>This layer is responsible for receiving calls from our SPA. When it comes to scalable back-end Applications it’s important to take into consideration the following:</p><ol><li>Using a dedicated database only for this layer is very important (Optional: Consider having a database for reading and another one for writing database. e.g. MongoDB for Reading and SQL Server for writing)</li><li>If the backend needs to store data received via frontend consider using a Bucket for it.</li><li>Consider using the known patterns used by the community as Rest, GraphQL, or RPC.</li></ol><h3>Backend</h3><p>The idea here is to create a Rails API to communicate directly with the front end then we can imagine some endpoints to list the characters and another one to receive the vote information. We will split the APIs into 2 different applications, As we are applying ideas according to scalable applications we must have 1 database for each of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/726/1*P_Ak4by-gyy8NrB98qn6dA.png" /><figcaption>A graphical example of the APIs for better understanding</figcaption></figure><h4>1. Characters API Endpoints</h4><pre>+------+----------------+-------------------------+------------------------+<br>| verb |    endpoint    |      request body       |      description       |<br>+------+----------------+-------------------------+------------------------+<br>| GET  | /v1/characters |                         | Listing of characters  |<br>| POST | /v1/characters | { &quot;name&quot;: &quot;Name Here&quot; } | Create a new character |<br>+------+----------------+-------------------------+------------------------+</pre><h4>2. Voting API Endpoints</h4><pre>+------+-----------+-----------------------+------------------+<br>| verb | endpoint  |     request body      |   description    |<br>+------+-----------+-----------------------+------------------+<br>| GET  | /v1/votes |                       | Listing of votes |<br>| POST | /v1/votes | { &quot;character_id&quot;: 1 } | Create a vote    |<br>+------+-----------+-----------------------+------------------+</pre><p>To receive tons of requests we can use <a href="https://sidekiq.org/">Sidekiq</a> to enqueue this data to persist the vote via background job, Having said this, when the user calls the <strong>POST</strong> <em>/v1/votes </em>in Voting<em> </em>API<em> </em>it will create a Sidekiq background job in a queue which can prevent that the database receives this vast quantity of work to do quickly and make the inserts on each API call, instead, we will receive the user’s request and add it to a process queue to be processed one by one as shown in the picture below.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4wBFm9CnFb4cgAjW6mM6iw.png" /><figcaption>A graphical flux of voting from the frontend to the backend</figcaption></figure><p>Okay but, when exactly do I need to use this kind of approach for storing data in the database?</p><p>Well, when you have lots of database usage (e.g. inserts, updates) per request and this is causing slowdowns making the database unavailable, connection errors with your database and the back-end, or even database locks, then it is an excellent approach to avoid these kinds of issues.</p><p>Also, bear in mind that Sidekiq is not the only tool for making background tasks, there are also lots of tools that provide queueing solutions such as RabbitMQ, SQS, Kafka, etc…</p><h3>Scalability</h3><p>Below we are going to talk about two different ways of scaling, Horizontal and Vertical.</p><h4>1. Vertical scale</h4><p>Let’s imagine a simple example using an <strong>AWS EC2</strong> instance with <strong>m7g.medium</strong> size that has <strong>1 vCPU</strong> and <strong>4 GB of RAM </strong>then<strong> </strong>we<strong> </strong>notice some peaks of memory usage on our application and you feel that <strong>4GB</strong> is not enough, and will be needed to increase the amount of <strong>RAM</strong> to maintain the Application running as expected, this kind of change is considered a vertical scale.</p><blockquote>Vertical scaling is the act of increasing or decreasing the machine resources like RAM, HD, CPU etc. even if it is a virtual machine or container.</blockquote><p>For example, the changes in <strong>HD space </strong>(from 10GB to 20GB of space), <strong>HD type</strong> (from HDD to SSD/SSD NVMe), and number of <strong>CPUs</strong> (from 1 CPU to 2 CPUs).</p><h4>2. Horizontal scale</h4><p>Horizontal scaling is very different from vertical scaling because you can use a load balancer layer to split the application charge between multiple application nodes as shown in the picture below. Before continuing with horizontal scale let’s learn a little bit about load balancer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CTVNboIxKNb08nIGVmO_vw.png" /><figcaption>Balancer use case</figcaption></figure><p>We notice that the load balancer can redirect the request to a specific node based on the usage of resources, yet, it is responsible for exposing the application URL.</p><blockquote>Horizontal scaling is the act of increasing or decreasing the number of nodes used by a load balancer.</blockquote><p>We can apply this in a real-world case, e.g. when the number of Application charges increases the number of nodes must follow the application charges increasing the number of nodes, otherwise, the number of nodes will need to be decreased to save the machine resources available and also decrease the infra’s costs. This kind of scaling can be done manually (by a human) or automatically (using an autoscale solution). I do not recommend handling this manually as we already have lots of solutions we can set the minimum and maximum number of nodes we want to use and the autoscale takes care of that magically (Docker services, Kubernetes pods, etc.).</p><p>For high-availability Applications, horizontal scaling is crucial because we can increase the number of nodes on demand to sustain the peaks of requests without affecting the Application performance.</p><h3>Architecture design</h3><p>After all of this, let&#39;s see what it would be graphically below. The idea here is only to understand the logic behind building scalable ecosystems, not the tooling (e.g. Docker, Kubernetes, etc.). Once you get this, it can be applied to any solution.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5p_8Y7GJJj7bRiouti5gEQ.png" /><figcaption>Voting Application Graphical Representation</figcaption></figure><p>For the front end, we will use Ngnix or Apache to serve the static files of our SPA that we can scale if needed.</p><p>For the back-end, we can use a load balancer layer ahead of the nodes to make horizontal scalability possible, In addition, some instances for the Sidekiq Workers to make the voting data persistence faster, the most instances you have for it the best, however, it increases the costs then it&#39;s good to see a comfortable and cost-benefit number of the instances.</p><p>For the back-end database, there are some cluster solutions for almost all databases available in the market now (Mysql, SQL Server, MongoDB, etc.), then, bear in mind to use it aiming the future needs of your Applications.</p><p>In conclusion, by applying this type of concept your application will be able to scale on demand preventing instabilities and unavailability taking advantage of horizontal scaling.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c4062396cecb" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A simple way to implement Redux using Redux Toolkit]]></title>
            <link>https://medium.com/@diegomelo_92702/a-simple-way-to-implement-redux-using-redux-toolkit-6a98f953e554?source=rss-73f118f83f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/6a98f953e554</guid>
            <category><![CDATA[front-end-development]]></category>
            <category><![CDATA[redux-toolkit]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[redux]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Diego Leite]]></dc:creator>
            <pubDate>Thu, 26 Jan 2023 11:02:29 GMT</pubDate>
            <atom:updated>2023-01-26T11:02:29.070Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KvALRW-N_3YCEwN08cF-eA.jpeg" /></figure><blockquote>First of all, bear in mind that this article is for those who know Redux deeply, and I won’t explain the Redux implementation from scratch, my intention is present the differences between Redux with Ducks’ pattern vs Redux with Redux Toolkit.</blockquote><p><strong>Have you been working on a legacy and complex project which has Redux implemented and want to simplify the code?</strong> or <strong>Have you noticed that Redux makes sense on your current project that doesn’t have global state management yet?</strong></p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2Fl41m0C1K4jVD5vQsM%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2Fgiftdelivery-l41m0C1K4jVD5vQsM&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2Fl41m0C1K4jVD5vQsM%2Fgiphy.gif%3Fcid%3D790b761172ba7efbda8a1fe47899c91f5ade17eb0953d5ce%26rid%3Dgiphy.gif%26ct%3Dg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="326" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d0940db929596287dd78f9a48ed35bf/href">https://medium.com/media/0d0940db929596287dd78f9a48ed35bf/href</a></iframe><p>When I had my first contact with Redux I got a little bit lost in terms of file structure and the way that Redux worked then I get started to learn its concepts which make my life easy, however, the thing that annoyed me a lot was the complexity to setup, and, maintain the code clear even with the project’s growth.</p><p>I found the Ducks pattern which was an approach more simple and workless in comparison with the first Redux approach that had directories for types, actions, and, reducer, etc… therefore I wasn’t completely satisfied yet… so I found the Redux Toolkit and it is what I was looking for all of these years.</p><p>Let’s start with an example of Ducks’ pattern implementation, in this case, I will create a simple state called <strong>car</strong> as shown below.</p><pre>// src/redux/ducks/car.js<br><br>// actions<br>const CREATE = &#39;your-app-name-here/car/CREATE&#39;;<br>const UPDATE = &#39;your-app-name-here/car/UPDATE&#39;;<br>const REMOVE = &#39;your-app-name-here/car/REMOVE&#39;;<br><br>const initialState = {<br>    data: [],<br>}<br><br>// reducer<br>export default function reducer(state = initialState, action = {}) {<br>  switch (action.type) {<br>    // reducer conditions<br>    case CREATE:<br>      return { data: [...state.data, action.payload] };<br>    case UPDATE:<br>      const { id, value } = action.payload;<br>      comst data = state.data.map((item) =&gt; {<br>        if (item.id === id) return value;<br><br>        return item;<br>      })<br>      return { data };<br>    case REMOVE:<br>      comst data = state.data.filter((item) =&gt; item.id != action.payload)<br>      return { data };<br><br>    default: return state;<br>  }<br>}<br><br>// action creators<br>export function createCar(payload) {<br>  return { type: CREATE, payload };<br>}<br><br>export function updateCar(payload) {<br>  return { type: UPDATE, payload };<br>}<br><br>export function removeCar(payload) {<br>  return { type: REMOVE, payload };<br>}<br><br>// async call. Ex. call an api endpoint using thunk<br>export function fetchCar() {<br>  return dispatch =&gt; get(&#39;/car&#39;).then((car) =&gt; dispatch(updateCar(car)))<br>}</pre><p>We can notice that using this approach we need to care about the <strong>types</strong>, <strong>actions</strong>, and <strong>conditions</strong> for every type that we have inside the car Redux state, which in the simple state is an easy task to do, however, if we have a complex state this probably will be like “skating in thin ice”.</p><p>Therefore, we can see an implementation of this same car Redux state using Redux Toolkit below.</p><pre>import { createSlice } from &#39;@reduxjs/toolkit&#39;<br><br>export const carSlice = createSlice({<br>  name: &#39;car&#39;,<br>  initialState: {<br>    data: [],<br>  },<br>  reducers: {<br>    createCar: (state, action) =&gt; {<br>      state.data.push(action.payload)<br>    },<br>    updateCar: (state, action) =&gt; {<br>      const { id, value } = action.payload<br>      state.data.map((item) =&gt; {<br>        if (item.id === id) return value<br><br>        return item<br>      })<br>    },<br>    removeCar: (state, action) =&gt; {<br>      state.data.filter((item) =&gt; item.id != action.payload)<br>    },<br>  },<br>})<br><br>export const { createCar, updateCar, removeCar } = carSlice.actions<br><br>export const fetchCar = () =&gt; (dispatch) =&gt; {<br>  fetch(&#39;/car&#39;).then((car) =&gt; dispatch(updateCar(car)))<br>}<br><br>export default carSlice.reducer</pre><p>As you can see above, by using Redux Toolkit you don’t need to care about the types and actions anymore because they can be defined inside of the reducers property in a way more simple.</p><p>Another difference is the way that we can manage the state itself, in this example as we have the data property which is an array we can use the push function directly which is impossible using the Ducks’ pattern approach because the Redux state is immutable and the switch that we usually do inside of the reducer needs to return the new changed state.</p><p>In conclusion, we can see the differences between implementations that use <a href="https://github.com/erikras/ducks-modular-redux">Ducks’ pattern</a> and the ones that use Redux Toolkit, for more information about the Redux toolkit click <a href="https://redux-toolkit.js.org/">here</a>.</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FV2ZrZfHghzSNi%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fgiphy.com%2Fgifs%2FV2ZrZfHghzSNi&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExNGNiNDRmOGViMDU4ZTcwZDA3NmE3YzJiODZkNjZkNzFjMzU1NmQ1OSZjdD1n%2FV2ZrZfHghzSNi%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="327" frameborder="0" scrolling="no"><a href="https://medium.com/media/e59b6a7be679d73a6bb475cdfe52a8de/href">https://medium.com/media/e59b6a7be679d73a6bb475cdfe52a8de/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6a98f953e554" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ruby IntelliSense on VS Code with Solargraph]]></title>
            <link>https://medium.com/@diegomelo_92702/ruby-intellisense-on-vs-code-with-solargraph-c1bea883561e?source=rss-73f118f83f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1bea883561e</guid>
            <category><![CDATA[solargraph]]></category>
            <category><![CDATA[vscode-extension]]></category>
            <category><![CDATA[debugging]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[vscode]]></category>
            <dc:creator><![CDATA[Diego Leite]]></dc:creator>
            <pubDate>Wed, 03 Nov 2021 13:22:32 GMT</pubDate>
            <atom:updated>2021-11-03T13:22:32.408Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*W7y3LfilgsLse6HrvAJuVQ.jpeg" /></figure><p>In this article, I will explore some features of Solargraph on VS Code and how to configure it in your development environment.</p><p>Before we start I will explain some features of Solargraph, and after following these steps below, I will show how to configure it on VS Code.</p><h4>What is Solargraph?</h4><p>Solargraph is a language server that provides IntelliSense, code completion, and inline documentation for Ruby.</p><h4>What are the benefits of using Solargraph?</h4><p>If you worked with any IDE you’ve noted that the behavior when you are coding on them instead of coding on a generic notepad, features like code completion, type checking, and code navigation makes our lives easier. Solargraph goes through this way and tries brought to an IDE-like experience to VS Code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/500/0*0q2Uk2lX3gpOeWYT.gif" /><figcaption>Solargraph in action on VS Code</figcaption></figure><p>Who knows me know that I like to code in TypeScript, and the way TypeScript IntelliSense works on VS Code, then I searched for a tool that has the same behavior in VS Code in Ruby projects, amid the searching I’ve found <a href="https://solargraph.org/">Solargraph</a> gem.</p><h4>Let’s get started!</h4><p>First of all, make sure if you have the Solargraph gem has been installed, or if you didn’t it follow the steps below.</p><p>Install the gem from the command line:</p><pre>$ gem install solargraph</pre><p>Or add it to your Gemfile:</p><pre>gem &#39;solargraph&#39;, group: :development</pre><p>In the next step, you will install the <strong>Solargraph</strong> plugin on your <strong>VSCode</strong>, install it using the link below.</p><p><a href="https://marketplace.visualstudio.com/items?itemName=castwide.solargraph">Ruby Solargraph - Visual Studio Marketplace</a></p><p>Make sure if you have followed all of the last steps to start to configure the solargraph on your project.</p><p>Inside of your <strong>VSCode settings.json </strong>file<strong>, </strong>I recommend that you insert these lines below:</p><pre>// settings.json<br>{<br>  <em>&quot;solargraph.transport&quot;</em>: &quot;stdio&quot;,<br>  <em>&quot;solargraph.formatting&quot;</em>: true,<br>  <em>&quot;solargraph.diagnostics&quot;</em>: true<br>}</pre><p>Run the command below to generate the <strong>.solargraph.yml</strong> file on the root of your project.</p><pre>$ solargraph config</pre><p>Ok, now you have the <strong>.solargraph.yml</strong> file on the root of your project with this content below.</p><pre># .solargraph.yml</pre><pre>---<br>include:<br>- &quot;**/*.rb&quot;<br>exclude:<br>- spec/**/*<br>- test/**/*<br>- vendor/**/*<br>- &quot;.bundle/**/*&quot;<br>require: []<br>domains: []<br>reporters:<br>- rubocop<br>- require_not_found<br>formatter:<br>  rubocop:<br>    cops: safe<br>    except: []<br>    only: []<br>    extra_args: []<br>require_paths: []<br>plugins: []<br>max_files: 5000</pre><h4>include</h4><p>A list of directory globs to include in Solargraph’s code maps. The default configuration includes all .rb files in the folder.</p><h4>exclude</h4><p>A list of directory globs to exclude from Solargraph’s code maps. The default configuration excludes the spec, test, and vendor folders.</p><h4>require</h4><p><strong>Note:</strong> Consider adding requires with a YARD @!parse directive instead of using this configuration setting.</p><p>Use require to add required paths that are not explicitly defined in code.</p><p><strong>Example:</strong></p><pre>require:<br>- sinatra/base</pre><p>Solargraph will act as if a file in the project contained the line require &#39;sinatra/base&#39;.</p><h3>domains</h3><p>Solargraph will use the designated classes and modules as contexts in which the project’s scripts will run. For example: if one of the domains is Class&lt;Sinatra::Base&gt;, the Sinatra DSL will be included in suggestions. (Whether you need to specify the domain inside Class&lt;&gt; depends on how the library is implemented.)</p><h3>reporters</h3><p>Solargraph provides diagnostics reporters to send diagnostics to the client. The reporters section selects<br>which reporters the language server should use:</p><pre>reporters:<br>- rubocop<br>- require_not_found</pre><p>rubocop enables RuboCop linting. Its rules can be configured in a .rubocop.yml file.</p><p>require_not_found highlights require calls where Solargraph could not resolve a required path. Note that this error does not necessarily mean that the path is incorrect; only that Solargraph was unable to recognize it.</p><p>typecheck will report problems with type tags. See <a href="https://solargraph.org/guides/type-checking">Type Checking</a> for more information.</p><p>You can use all! to tell the language server to use all available reporters.</p><p>Run solargraph reporters for a complete list of available reporters and their descriptions.</p><p>I recommend that you use those reporters on your solargraph config file:</p><pre># .solargraph.yml</pre><pre>...<br>reporters:<br>- rubocop<br>- require_not_found<br>- typecheck:strict<br>...</pre><p>I’ve created a class using <a href="https://yardoc.org/">YARD</a> for this example to show you the solargraph <strong>type checking</strong> in use on <strong>VS Code, </strong>you can see the code below.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/6a584410bd2bb45369ad5b3ffaf4f2ec/href">https://medium.com/media/6a584410bd2bb45369ad5b3ffaf4f2ec/href</a></iframe><h4>Hands-on</h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FZVik7pBtu9dNS%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FZVik7pBtu9dNS%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FZVik7pBtu9dNS%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="242" frameborder="0" scrolling="no"><a href="https://medium.com/media/98320c862b2e285ee70810a5e350c5ac/href">https://medium.com/media/98320c862b2e285ee70810a5e350c5ac/href</a></iframe><p>Here below we can see how the type checking works when we instantiate the Car class.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*Bc__kvAng-01m9hQAqsJpQ.gif" /></figure><p>If you want to see more or try to test it, I’ve created a GitHub repository with these Solargraph configurations.</p><p><a href="https://github.com/diegomelo182/solargraph-example">diegomelo182/solargraph-example (github.com)</a></p><h3>That’s all folks!!!</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FlD76yTC5zxZPG%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FlD76yTC5zxZPG%2Fgiphy.gif&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FlD76yTC5zxZPG%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="319" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb051abb3b03b93b790cc77394565546/href">https://medium.com/media/bb051abb3b03b93b790cc77394565546/href</a></iframe><p>My name is <strong>Diego Melo, </strong>I’m a <strong>developer</strong>, <strong>Brazilian</strong> and I hope this content was helpful for you.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1bea883561e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to use attr_reader, attr_writer, and attr_accessor on your Ruby Class]]></title>
            <link>https://medium.com/@diegomelo_92702/how-to-use-attr-reader-attr-writer-and-attr-accessor-on-your-ruby-class-50ebc6d5b68f?source=rss-73f118f83f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/50ebc6d5b68f</guid>
            <category><![CDATA[ruby-on-rails-development]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[object-oriented]]></category>
            <dc:creator><![CDATA[Diego Leite]]></dc:creator>
            <pubDate>Thu, 30 Sep 2021 20:28:53 GMT</pubDate>
            <atom:updated>2021-10-05T14:24:04.740Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*iS_dZG3mR840v7P1qSluiw.png" /></figure><p>First of all, my name is <strong>Diego Melo</strong>, and I will show you how to use the <strong>getters</strong> and <strong>setters</strong> by Ruby way. To turns it more understandable I will start showing an example using <strong>TypeScript</strong> because it is a <strong>strongly</strong> <strong>typed language</strong> (yes I know, it’s a javascript superset).</p><p>Here we have a simple class called “<strong>Car”</strong>, and it has only one property called “<strong>name”</strong> of <strong>string type</strong> and <strong>private</strong>, which means the property may only be accessed by own class, in case of inheriting the child class can’t access “<strong>name</strong>” directly using the “<strong>this</strong>”.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8246edbbd054fdf200435ae73b24cf52/href">https://medium.com/media/8246edbbd054fdf200435ae73b24cf52/href</a></iframe><p>So, I’ve declared 2 methods (<strong>setName</strong> and <strong>getName</strong>) to manipulate the “<strong>name</strong>” property and I’ve set them as <strong>public</strong>, which will grant that these 2 methods can be accessed by any scope without limitations.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/378/1*mjMIzSRmtHVm0V2ZPB8BKQ.png" /></figure><p>So there we can see that we’ve used the method <strong>setName</strong> to set a new value to the “<strong>name</strong>” property in the “<strong>Car class</strong>” without accessing the property directly, and in the <strong>getName</strong> method we have the same behavior, but instead of setting a new value in the “<strong>name</strong>” property, we got its value.</p><blockquote>Well, now we learned how <strong>getters</strong> and <strong>setters </strong>methods<strong> </strong>work, then let’s start with <strong>attr_accessor </strong>and how it works</blockquote><h3>attr_accessor</h3><p>In Ruby, we can do the same thing in only one line, look at this code below:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f2f832275fe024e4b20ebc1add8002a7/href">https://medium.com/media/f2f832275fe024e4b20ebc1add8002a7/href</a></iframe><p>When you use “<strong>attr_accessor”</strong> in a ruby class it’s the same thing that does a <strong>getter </strong>and <strong>setter </strong>methods (<strong>getName</strong> and <strong>setName </strong>that we’ve seen before) inside your class, but you don’t need to define them because it will occur implicitly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*JDZBEn2L2PUGyxVO2MfEDQ.gif" /><figcaption>attr_accessor example</figcaption></figure><h3>attr_reader</h3><p>When we using <strong>attr_reader</strong> the Ruby only initializes the <strong>getter</strong> method, that is, that we can’t change the value of the property, only to read its value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/aa91927032bfe1f027a10131f2ae77d6/href">https://medium.com/media/aa91927032bfe1f027a10131f2ae77d6/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*w9ESrjyfwSx4sfESV7UN5A.gif" /><figcaption>attr_reader example</figcaption></figure><h3>attr_writer</h3><p>Finally, when we using <strong>attr_writer</strong> the Ruby only initializes the <strong>setter</strong> method, in other words, that we can’t read the value of the property, only to change its value.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a0ed1d7c45603d3b70f8923ba756708/href">https://medium.com/media/8a0ed1d7c45603d3b70f8923ba756708/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/395/1*McOSoNaGa3UGHtx5FbemIw.gif" /><figcaption>attr_writer example</figcaption></figure><h4><strong>That’s all guys! I hope </strong>this article<strong> was helpful for you.</strong></h4><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FkaBU6pgv0OsPHz2yxy%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FkaBU6pgv0OsPHz2yxy%2Fgiphy.gif%3Fcid%3Decf05e473tfmhs11fwciqlk74677oupb6tng6uwlpyuwg5ev%26rid%3Dgiphy.gif%26ct%3Dg&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FkaBU6pgv0OsPHz2yxy%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="435" frameborder="0" scrolling="no"><a href="https://medium.com/media/40c15b5039fd94004d20634f8eac611e/href">https://medium.com/media/40c15b5039fd94004d20634f8eac611e/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=50ebc6d5b68f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Getting started with React Hooks Context API]]></title>
            <link>https://medium.com/@diegomelo_92702/getting-started-with-react-hooks-context-api-6245d5570089?source=rss-73f118f83f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/6245d5570089</guid>
            <category><![CDATA[javascript-tips]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[reactjs]]></category>
            <category><![CDATA[react-hook]]></category>
            <category><![CDATA[javascript]]></category>
            <dc:creator><![CDATA[Diego Leite]]></dc:creator>
            <pubDate>Tue, 21 Sep 2021 04:57:58 GMT</pubDate>
            <atom:updated>2021-09-28T15:02:40.362Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*0xrNZWGDBNvscNKpQw76YA.png" /></figure><p>Before we start with this subject, I will introduce myself, I’m <strong>Brazilian</strong>, my name is <strong>Diego Melo</strong> and I’ve been coding since 2012, so <strong>this is my first English article</strong> about software development. I hope you all appreciate this content.</p><h3><strong>Let’s get started!</strong></h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FC910Lc34NT49PQrtqn%2Fvideo&amp;display_name=GIPHY&amp;url=https%3A%2F%2Fgiphy.com%2Fclips%2Fwizard-joelfox-joel-fox-C910Lc34NT49PQrtqn&amp;image=https%3A%2F%2Fmedia1.giphy.com%2Fmedia%2FC910Lc34NT49PQrtqn%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="480" height="270" frameborder="0" scrolling="no"><a href="https://medium.com/media/4b4dfbd79a114d52fee1122f301f6e77/href">https://medium.com/media/4b4dfbd79a114d52fee1122f301f6e77/href</a></iframe><p>First of all, I will explain more about why you need to use <strong>Context API </strong>on your professional or personal project and your benefits below:</p><ol><li>Centralizes your state in one place, if you want.</li><li>Creates different states by context.</li><li>Simplifies pass the state from parents components to children components, because you don’t need to use props to do that.</li></ol><p>Initially, I created my context called <strong>ItemsContext </strong>(line 3) using <strong>createContext </strong>hook and I set your initial state with 3 properties: <strong>items</strong>, <strong>createItem</strong>, and <strong>removeItem</strong>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/bb08a0447c9fbeb84bb46bd64362b089/href">https://medium.com/media/bb08a0447c9fbeb84bb46bd64362b089/href</a></iframe><p>Posteriorly, I decided to create a component with <strong>children </strong>prop and using <strong>useState </strong>hook that I will put into the item context on the next step. We noted that <strong>ItemsContext.Provider</strong> has a <strong>prop </strong>called <strong>value </strong>too, and over there we can pass what we want, in this case, I passed items variable from <strong>useState</strong>, and 2 other functions called <strong>createItem </strong>and <strong>removeItem </strong>that uses <strong>setItem </strong>function of <strong>useState </strong>hook. So, I can use <strong>ItemsProvider </strong>component to provide the item context to your children components.</p><p>We noted that I export the <strong>ItemContext </strong>too, that’s ok, I will show you the reason why I did it.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43b339bb94578408569fa7b51e93424b/href">https://medium.com/media/43b339bb94578408569fa7b51e93424b/href</a></iframe><p>In this example, I imported the <strong>ItemsProvider </strong>component on my main component called <strong>App</strong>, which means all children components of my application will have access to item context and don’t need to use component props to do that.</p><h3><strong>That’s great!</strong></h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F3oz8xA3jxNGlMPI83m%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F3oz8xA3jxNGlMPI83m%2Fgiphy.gif%3Fcid%3Decf05e471j47k37pa0tu1ygiqowarkhai8p112p2elz6dh2q%26rid%3Dgiphy.gif%26ct%3Dg&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2F3oz8xA3jxNGlMPI83m%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/b63f09494ab096f46f1b9ad8c208ca61/href">https://medium.com/media/b63f09494ab096f46f1b9ad8c208ca61/href</a></iframe><p>Now I will show you how to read the field called <strong>items </strong>of the <strong>ItemsContext</strong>. Initially, I imported <strong>useContext </strong>(line 1) of react and <strong>ItemsContext </strong>(line 4) from the context file that I’ve explained before.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9684c52c16fccbb9974ffb0e661176e/href">https://medium.com/media/c9684c52c16fccbb9974ffb0e661176e/href</a></iframe><p>So, now we can see the use of <strong>useContext </strong>inside of <strong>ItemsList </strong>component and the way I get the values that we saw on <strong>ItemsContext.Provider</strong>. We noted that we can use the <strong>removeItem</strong> function normally and how it changes the state of <strong>items </strong>variable when we pass the index that we want to remove.</p><p>Here we saw the way I used the createItem function to insert the values of a simple formik form into the items variable inside of ItemsContext.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dc168cc8ccc201ae940a30fbf4da5747/href">https://medium.com/media/dc168cc8ccc201ae940a30fbf4da5747/href</a></iframe><p>As we have seen before, we need to import the <strong>ItemsContext </strong>and <strong>useContext </strong>again, which means on line 9 I get the <strong>createItem </strong>function, and we can call then on form submit on line 18, so the <strong>items </strong>variable will change inside <strong>ItemsContext</strong>. So our <strong>ItemsList </strong>component will be affected with the <strong>items </strong>variable as well, and we don’t need to use the props of the component any time.</p><h3>That’s all folks!!!</h3><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FxUPOqo6E1XvWXwlCyQ%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2FxUPOqo6E1XvWXwlCyQ%2Fgiphy.gif%3Fcid%3Decf05e47uo4ptn1y137e6e5dq4e5m4fg5ag6t6knu326uyk1%26rid%3Dgiphy.gif%26ct%3Dg&amp;image=https%3A%2F%2Fi.giphy.com%2Fmedia%2FxUPOqo6E1XvWXwlCyQ%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="244" frameborder="0" scrolling="no"><a href="https://medium.com/media/a7231a2bcfbfca52ea7c0793a88f32b9/href">https://medium.com/media/a7231a2bcfbfca52ea7c0793a88f32b9/href</a></iframe><p>I hope this article was useful to you!!!</p><p>For more information, access here the GitHub repository with this example below:</p><p><a href="https://github.com/diegomelo182/react-context-api-sample">diegomelo182/react-context-api-sample (github.com)</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6245d5570089" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Ótimo artigo, parabéns!]]></title>
            <link>https://medium.com/@diegomelo_92702/%C3%B3timo-artigo-parab%C3%A9ns-fd34fbb50ced?source=rss-73f118f83f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd34fbb50ced</guid>
            <dc:creator><![CDATA[Diego Leite]]></dc:creator>
            <pubDate>Mon, 12 Apr 2021 17:05:35 GMT</pubDate>
            <atom:updated>2021-04-12T17:05:35.399Z</atom:updated>
            <content:encoded><![CDATA[<p>Ótimo artigo, parabéns!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd34fbb50ced" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Como eu integrei o Rails 5 API + JWT + Angular - Parte 1]]></title>
            <link>https://medium.com/@diegomelo_92702/como-eu-integrei-o-rails-5-api-jwt-angular-parte-1-eaac214b7a5b?source=rss-73f118f83f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/eaac214b7a5b</guid>
            <category><![CDATA[angular]]></category>
            <category><![CDATA[api]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[angular2]]></category>
            <category><![CDATA[rails]]></category>
            <dc:creator><![CDATA[Diego Leite]]></dc:creator>
            <pubDate>Tue, 11 Apr 2017 18:26:17 GMT</pubDate>
            <atom:updated>2018-06-07T14:09:45.680Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/850/1*WmOu72jhPgvDqBNx7G6PGQ.png" /></figure><p>Antes de mais nada verifique se você possui o <strong>Rails 5 </strong>instalado em sua máquina, como o foco é mostrar a integração <strong>Rails + Angular</strong> não irei mostrar o processo de instalação e configuração do Ruby + Rails 5, para darmos início vamos fazer a inicialização do projeto Rails 5 com o comando:</p><blockquote>$ rails new my_api --api</blockquote><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*EV41NGrstMP7aJL0_EWQ2w.gif" /><figcaption>Tudo Ok! Vamos lá!</figcaption></figure><p>Note que usamos o parâmetro <strong>--api, </strong>ou seja, criamos o projeto sem a camada das views, pois iremos usar o Angular para isso. O próximo passo é instalar uma gem chamada <a href="https://github.com/cyu/rack-cors"><strong>rack-cors</strong></a><strong> </strong>para integrarmos a API com o Angular, para instalar a gem basta adicionar: <strong>gem ‘rack-cors’, :require =&gt; ‘rack/cors’</strong> no seu <strong>Gemfile </strong>em seguida<strong> </strong>digite o comando abaixo:</p><blockquote>$ bundle install</blockquote><p>O próximo passo é adicionar as configurações do <strong>Rack Cors </strong>no seu arquivo<strong> config.ru </strong>que se encontra na raiz do seu projeto, como no exemplo abaixo:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f554bc21f81a944bcdfc2e0e8dddadef/href">https://medium.com/media/f554bc21f81a944bcdfc2e0e8dddadef/href</a></iframe><p>Agora vamos criar o arquivo <strong>config/initializers/cors.rb </strong>caso não exista, caso exista basta inserir as configurações de <strong>origins</strong> e <strong>resource, </strong>como no arquivo abaixo:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f3d8cd43ce3fddf61652c0e6ebcfd908/href">https://medium.com/media/f3d8cd43ce3fddf61652c0e6ebcfd908/href</a></iframe><p>Note que o <strong>origins</strong> recebe um parâmetro <strong>‘*’,</strong> que indica que serão aceitas requisições de qualquer host independente do seu endereço, caso queira determinar o endereço que terá acesso a sua API basta substituir o * pelo endereço que deseja (exemplo: <strong>https://google.com</strong>), já no <strong>resources </strong>é onde é determinado os métodos que sua aplicação permitirá receber, como os conhecidos <strong>POST</strong> e <strong>GET</strong> por exemplo, além de determinar quais <strong>HEADERS</strong> poderão ser recebidos por sua API e enviados dela em caso de resposta, para definir qual <strong>HEADER</strong> você terá acesso na resposta use a chave <strong>expose e </strong>no valor da chave passe um array de strings com os nomes dos <strong>HEADERS </strong>no meu caso passei o <strong>&#39;Jwt-Token-Renewed&#39;</strong> no array onde usarei para renovar o <strong>JWT</strong> quando o mesmo estiver próximo de expirar na nossa aplicação Angular posteriormente.</p><p>Feito isso já temos o <strong>Rack Cors</strong> devidamente configurado, e nossa <strong>API</strong> já poderá ser acessada na nossa aplicação <strong>Angular</strong>, porém ainda teremos que instalar mais uma <strong>gem</strong> chamada <strong>jwt</strong>, instale com a gem inserindo a seguinte linha no seu <strong>Gemfile: gem &#39;jwt&#39;. </strong>Em seguida execute o seguinte comando no seu terminal:</p><blockquote>$ bundle install</blockquote><p>Pronto! Agora nossa aplicação Rails já pode fazer o <strong>encode</strong> e o <strong>decode</strong> do <strong>JWT, </strong>porém precisamos filtrar “todas” as requests e verificar se o token foi enviado no <strong>HEADER </strong>da requisição e se o token é válido, para isso nós faremos uma série de verificações no nosso <strong>application_controller.rb, </strong>mas antes vamos gerar um secret com o comando abaixo:</p><blockquote>$ rake secret</blockquote><p>Após executado o comando acima será mostrado um hash, copie ele, e agora vamos criar uma nova chave no arquivo <strong>config/secrets.yml</strong>, como estamos no enviroment de desenvolvimento, vamos adicionar a chave <strong>hmac_secret</strong> dentro do <strong>development</strong> e colar o hash que copiamos anteriormente como no exemplo abaixo:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8f95a0fcdef12ba45b3c1c3671ee8a4e/href">https://medium.com/media/8f95a0fcdef12ba45b3c1c3671ee8a4e/href</a></iframe><p>Note que os secrets da aplicação que eu criei foi substituído por <strong>“&lt;%= ENV[“SECRET_KEY_BASE”] %&gt;”</strong> sendo assim na sua aplicação deverá ter alguns hashs imensos ao envés disso, vale lembrar que os <strong>secrets</strong> como o nome já diz, são os segredos de sua aplicação e você não deve compartilha-los com ninguém, se você tiver uma aplicação em produção não é aconselhado deixar seus secrets dentro do repositório <strong>git</strong>, por questões de segurança deixe-os somente na máquina que você hospedou sua aplicação. Agora que salvamos nosso secret podemos resgata-los onde e quando quisermos na nossa aplicação Rails.</p><p>Voltando ao <strong>application_controller.rb</strong>, caso você não saiba o <strong>ApplicationController</strong> é o controller principal e os controllers gerados consequentemente herdarão dele, sendo assim faremos as verificações e validações necessárias no próprio, segue abaixo o <strong>application_controller.rb</strong> já pronto para ser implementado:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/7b5481409922ff4c0777250c764cc90b/href">https://medium.com/media/7b5481409922ff4c0777250c764cc90b/href</a></iframe><p>Note que eu usei o <strong>before_action</strong> no método <strong>jwt_auth_validation</strong>, isso significa que caso algum controller herde o <strong>ApplicationController, </strong>o método <strong>jwt_auth_validation </strong>será executado automaticamente antes de qualquer action do controller que herdou do <strong>ApplicationController</strong>, ou seja, dessa forma poderemos verificar se a request tem em seu <strong>HEADER</strong> o <strong>JWT token</strong> e se o mesmo é válido, sendo assim, permitir ou não o acesso às informações ou ações requisitadas. Nesse caso eu verifico se existe o header <strong>Authentication</strong> e faço as devidas verificações como: O token existe? É válido? Expirou? Possui um payload válido? E verifico caso falte 1 hora para o token atual expirar, que ele me gere outro token com validade renovada por mais 4 horas e me retorne no <strong>HEADER</strong> de qualquer resposta que venha a vir de qualquer controller que herde do <strong>ApplicationController,</strong> o<strong> </strong>token renovado é retornado no <strong>JWT-Token-Renewed </strong>dentro do<strong> HEADER </strong>de resposta. Preferi por as verificações no <strong>ApplicationController</strong> pelo fato de ser mais fácil de compreender o que foi feito, porém o correto seria criar um <strong>Concern</strong> e fazer um <strong>include</strong> no <strong>ApplicationController</strong>.</p><p>Bom agora que já temos o controller principal pronto, vamos criar um <strong>scaffold</strong> chamado <strong>users</strong>, no terminal digite:</p><blockquote>$ rails g scaffold user name:text email:text password_digest:string &amp;&amp; rake db:create db:migrate</blockquote><p>Pronto! Agora temos nosso primeiro scaffold gerado e note que a classe <strong>UserController</strong> já herda de <strong>ApplicationController</strong> automaticamente, sendo assim todas as verificações anteriores já surtirão efeito e não conseguiremos acessar o conteúdo do <strong>UserController</strong> sem autenticar, porém ainda não temos um controller para autenticação, sendo assim vamos criar um, digite o seguinte comando no terminal:</p><blockquote>$ rails g controller auth</blockquote><p>Agora que já temos o controller <strong>AuthController</strong> vamos criar um método para autenticar na nossa API, e vamos retirar o filtro do <strong>jwt_auth_validation</strong> na nossa classe com o <strong>skip_before_action</strong>, pois o nosso auth precisa ser público e não deve passar pelas verificações que fizemos no <strong>ApplicationController</strong>, segue abaixo o controller:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/dfa3a3e087aec819686bf73332b79fe8/href">https://medium.com/media/dfa3a3e087aec819686bf73332b79fe8/href</a></iframe><p>Agora que já temos o controller vamos na rota e adicionar uma entrada para esse controller utilizando <strong>POST</strong> para enviar os dados <strong>email</strong> e <strong>password</strong> para o endpoint <strong>&#39;user_auth&#39;</strong> da nossa API, abaixo segue a rota:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a393a073488e2e5fb24fe5e67c32b5e4/href">https://medium.com/media/a393a073488e2e5fb24fe5e67c32b5e4/href</a></iframe><p>Ok! Já temos o <strong>controller</strong> para autenticar e <strong>scaffold</strong> gerado para <strong>User</strong> porém para criptografar o campo <strong>password</strong> no nosso DB precisaremos adicionar o seguinte código ao nosso model <strong>User</strong>:</p><blockquote>has_secure_password</blockquote><p>Isso fará com que a coluna <strong>password_digest</strong> gerada no <strong>DB</strong> receba somente dados <strong>criptografados,</strong> para melhor segurança e privacidade da senha do usuário, e como usamos <strong>User</strong> para autenticar na nossa <strong>API</strong> será necessário fazer isso para usar o método <strong>authenticate</strong> da classe <strong>ActiveRecord </strong>no momento do <strong>POST</strong> da nossa autenticação.</p><p>Em seguida verifique se seu <strong>gemfile</strong> possui:</p><blockquote>gem ‘bcrypt’</blockquote><p>Caso não possua, o insira e execute:</p><blockquote>bundle install</blockquote><p>Pronto! Agora vamos criar um usuário padrão usando o <strong>seeds</strong> para que possamos testar nossa <strong>autenticação</strong> na nossa <strong>API</strong>, no seu arquivo <strong>db/seeds.rb</strong> adicione o seguinte código:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/43bb3f0fe8f993edd97a6c5e8f4eb38b/href">https://medium.com/media/43bb3f0fe8f993edd97a6c5e8f4eb38b/href</a></iframe><p>Ufaaa! Agora já temos a camada inicial da API concluída!!! =D</p><p>Vamos vamos testar nossa <strong>API</strong> no <strong>postman</strong>, vamos mandar um <strong>POST</strong> na rota <strong>user_auth</strong> passando os parâmetros: {“email”:”<a href="/service/mailto:user@email.com">user@email.com</a>”, “password”:”user@myapi”} e olha só o resultado:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/841/1*N35Jbh58_b0ftOlB3Fj3fg.png" /><figcaption>Token de autenticação retornado</figcaption></figure><p>Agora se colocarmos o token gerado na chave <strong>Authentication</strong> no <strong>Header</strong> para cada requisição da nossa <strong>API</strong> a aplicação vai saber que você já está autenticado e liberará o acesso a rota caso o token seja válido, o resultado da requisição com o token de autenticação abaixo:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/849/1*p9peb6jJu7ypomswiXYUCw.png" /></figure><p>Bom pessoal por hora é isso! Na segunda parte desse post faremos a integração da nossa <strong>API</strong> com o <strong>Angular 4,</strong> vou deixar o link do repositório do <strong>github</strong> para você dar uma conferida no código da aplicação.</p><p><a href="https://github.com/diegomelo182/my_api">diegomelo182/my_api</a></p><p>Até breve! =)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eaac214b7a5b" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Relacionamentos contemporâneos]]></title>
            <link>https://medium.com/@diegomelo_92702/relacionamentos-contempor%C3%A2neos-a395fcd1a5ed?source=rss-73f118f83f23------2</link>
            <guid isPermaLink="false">https://medium.com/p/a395fcd1a5ed</guid>
            <category><![CDATA[relacionamentos]]></category>
            <category><![CDATA[contemporary-romance]]></category>
            <dc:creator><![CDATA[Diego Leite]]></dc:creator>
            <pubDate>Tue, 04 Oct 2016 14:26:44 GMT</pubDate>
            <atom:updated>2016-10-04T14:31:26.322Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cYs-dOr_ci7zX7x3wZK2Dw.jpeg" /></figure><p>Meu olhar superficial dos relacionamentos do século XXI, será mesmo que o amor eros morreu? Pois bem, o que mais vemos nas novelas de hoje em dia? Banalização dos relacionamentos como um todo, a pessoa que se apaixona por outra já comprometida e que consegue acabar com toda a história do casal para tê-la, e isso não é diferente fora das telinhas (e ainda me perguntam porque não assisto TV?).</p><p>Relacionamentos que acabam na primeira fase ruim, pois é, com a banalização dos relacionamentos já “abraçada” pela sociedade atual fica cada vez mais raro encontrar pessoas que realmente “vistam a camisa” e fiquem ali do seu lado mesmo quando a situação financeira não está favorável ou quando mesmo com raiva da briga feia que tiveram pela manhã no auge do seu relacionamento que já dura 5 anos continuam ali firmes e fortes, pois afinal é mais fácil desistir do que aceitar o lado ruim do outro, quem ama de verdade aceita o outro como ele realmente é e está.</p><p>E assim seguimos num mundo onde pessoas e relacionamentos são mais descartáveis que copinhos de café expresso, é triste perceber que a sociedade tende a sucumbir e pessoas estão cada vez mais superficiais, sem vida e sem cor…</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a395fcd1a5ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>