<?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 Clément Morisset on Medium]]></title>
        <description><![CDATA[Stories by Clément Morisset on Medium]]></description>
        <link>https://medium.com/@clementrollon?source=rss-b4867967e30b------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*QLPO9O-mZ3m3Vnym.</url>
            <title>Stories by Clément Morisset on Medium</title>
            <link>https://medium.com/@clementrollon?source=rss-b4867967e30b------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 12:48:17 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@clementrollon/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[Introducing Pry-Byetypo ]]></title>
            <link>https://medium.com/@clementrollon/introducing-pry-byetypo-e237d8ffa700?source=rss-b4867967e30b------2</link>
            <guid isPermaLink="false">https://medium.com/p/e237d8ffa700</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[productivity]]></category>
            <category><![CDATA[gem]]></category>
            <category><![CDATA[pry]]></category>
            <category><![CDATA[repl]]></category>
            <dc:creator><![CDATA[Clément Morisset]]></dc:creator>
            <pubDate>Thu, 22 Feb 2024 02:36:09 GMT</pubDate>
            <atom:updated>2024-02-22T02:36:09.235Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’re anything like me, it’s likely that you have sausage-like fingers.🌭<br>As a result, you might find yourself making typos on your REPL daily.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/956/1*M86rFlx84y4z-b-dABWqdg.gif" /></figure><p>This is why I am thrilled to introduce <a href="https://github.com/morissetcl/pry-byetypo"><strong>Pry-Byetypo</strong></a><strong>.<br></strong>It is a small Pry plugin who captures exceptions that may arise from typos and deduces the correct command based on your database information and session history.</p><p>For a while, Ruby has come with the useful <a href="https://github.com/ruby/did_you_mean"><strong>DidYouMean</strong></a> gem. It’s likely that you’ve already experienced it. It suggests potential commands for you to run.</p><pre>irb(main):001&gt; methodss<br>(irb):1:in `&lt;main&gt;&#39;: undefined local variable or method `methodss&#39; for main:Object (NameError)<br>Did you mean?  methods<br>               method<br> from /Users/clementmo/.rbenv/versions/3.2.2/lib/ruby/gems/3.2.0/gems/irb-1.11.1/exe/irb:9:in `&lt;top (required)&gt;&#39;<br> from /Users/clementmo/.rbenv/versions/3.2.2/bin/irb:25:in `load&#39;<br> from /Users/clementmo/.rbenv/versions/3.2.2/bin/irb:25:in `&lt;main&gt;&#39;<br>irb(main):002&gt;</pre><p>With <strong>Pry-Byetypo</strong>, we will autocorrect the command and run it in your REPL. For V1, we handle a few errors such as:</p><ul><li>NameError — undefined local variable or method</li><li>NameError — uninitialized constant</li><li>ActiveRecord::ConfigurationError</li><li>ActiveRecord::StatementInvalid</li></ul><p>I don’t want to spoil the <a href="https://github.com/morissetcl/pry-byetypo/tree/master">README</a>, so let’s just take a look at the <em>NameError: uninitialized constant</em> error with a basic example.</p><p>Without <strong>Pry-Byetypo</strong></p><pre>[2] pry(main)&gt; Account::Usert.last<br>NameError: uninitialized constant Account::Usert<br>from (pry):2:in `__pry__&#39;<br>[3] pry(main)&gt;</pre><p>With <strong>Pry-Byetypo</strong></p><pre>[2] pry(main)&gt; Account::Usert.last<br>I, [2024-01-13T20:00:16.280710 #694]  ERROR -- : uninitialized constant Account::Usert<br>I, [2024-01-13T20:00:16.281237 #694]  INFO -- : Running: Account::User<br>=&gt; #&lt;Account::User id: 1, email: &quot;yo@email.com&quot;&gt;</pre><p>What happens under the hood?</p><p>The first time you open a Pry instance with the gem installed, we will read your database to store the table names of your application into a <strong>byebug_dictionary.pstore</strong> file (utilizing PStore 🙌). <br>We then rely on the <strong>DidYouMean</strong> gem to find the closest match, update the command, and run the corrected one.</p><p>That’s it. 🤷‍♂</p><p>It’s worth noting that currently this plugin is not truly ORM-agnostic; to fully benefit from it, ActiveRecord is a must.</p><p>The gem is still in its infancy, and I plan to add more features in the future. If you have any suggestions, please <a href="https://github.com/morissetcl/pry-byetypo/issues">open an issue</a>. I hope you find it useful!</p><p>Bye bye typos 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=e237d8ffa700" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[It’s time to create your first lib of React components.]]></title>
            <link>https://medium.com/@clementrollon/its-time-to-create-your-first-lib-of-react-components-ef50b8c91610?source=rss-b4867967e30b------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef50b8c91610</guid>
            <category><![CDATA[npm]]></category>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[package]]></category>
            <category><![CDATA[react]]></category>
            <category><![CDATA[libraries]]></category>
            <dc:creator><![CDATA[Clément Morisset]]></dc:creator>
            <pubDate>Sun, 05 Jul 2020 14:33:06 GMT</pubDate>
            <atom:updated>2020-07-05T14:38:22.615Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/564/1*GDZ5j81eZRyO-77_06RjpQ.jpeg" /></figure><p>Sometimes you could find relevant to build you own UI component library. Main reasons are avoiding duplication between application or extracting UI from the logic. In my case I wanted to extract component for a React app. To be more accurate, I wanted to extract component for a Rails app where React was mounted with Webpack. Huge monolith don’t need necessary to gain extra weight with UI. So let’s extract them.</p><p>There is multiple ways to achieve it. Quickly I choose to go with a package named <strong>create-react-library</strong>, it’s pretty straigthforward, pretty well documented and relatively popular project.</p><pre><strong>npm install -g create-react-library <br>npx create-react-library &lt;your-package&gt;</strong></pre><p>By typing the last command you should answer at several questions like you package name, description etc.. nothing mandatory, if you leave them blank a default answer will be applied.</p><p>Once done, in the root of your project open two tabs in your terminal. In the first one run npm start and in the second one type cd example &amp;&amp; npm start . According to documentation:</p><blockquote>the first one will run rollup to watch your src/ module and automatically recompile it into dist/ whenever you make changes.&quot; And the second one will &quot;be running the example/ create-react-app that&#39;s linked to the local version of your module.</blockquote><p>If you go to localhost:3000you should see the default component.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*XKQ2X_3AqgIlKJ1DTrFWJQ.png" /></figure><p>Nice, you can start by playing with it or by adding your first component.</p><p>We are going to add a simple fake component, just an basic/ugly card (namely a square). I will let you the privilege to get it prettier. 😉</p><p>First we are going to create our component inside a component folder, so you can add src/components/Card.js with the minimal code below.</p><pre>import React from &quot;react&quot;;<br><br>const Card = props =&gt; {<br>  const { fontColor, backgroundColor, title } = props;<br>  const containerStyles = {<br>    height: 100,<br>    width: 100,<br>    backgroundColor: backgroundColor,<br>    color: fontColor,<br>    borderRadius: 10,<br>    margin: 10<br>  };<br>  const labelStyles = { color: fontColor };<br><br>  return (<br>    &lt;div style={containerStyles}&gt;<br>      &lt;span style={labelStyles}&gt;{ title }&lt;/span&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export { Card };</pre><p>As you can see you entry point is your index.js located in your src folder. So you have to modify this file by importing your component and deleting all the default content.</p><pre>export { Card } from ‘./components/Card’;</pre><p>Nice. But then you have to update your example application, located in example folder. In this way you could display you component.</p><p>So let’s modify example/src/Apps.jswith the code below.</p><pre>import React from “react”; <br>import { Card } from ‘myPackageName’; </pre><pre>const App = () =&gt; { <br>  return ( <br>    &lt;div&gt; <br>      &lt;div className=”App”&gt; <br>        &lt;Card fontColor={“white”} backgroundColor={‘grey’} title={“it’s a card”} /&gt; <br>      &lt;/div&gt;<br>    &lt;/div&gt; <br>  ); <br>}; </pre><pre>export default App;</pre><p>As create-react-library has <strong>livereload</strong> you should see the change directly on your screen, as below:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/908/1*FwabbKvCDjZjjhZybby7ig.png" /></figure><p>Let’s make it a bit more fun by adding <strong>hook</strong>. In src/components/Card.jswe are going add the following functionnal component:</p><pre>import React, { useState } from &quot;react&quot;;<br><br>const Card = props =&gt; {<br>  const { fontColor, title } = props;<br>  const [backgroundColor, setCardColor] = useState(&#39;red&#39;);<br>  const colors = [&#39;pink&#39;, &#39;red&#39;, &#39;green&#39;, &#39;yellow&#39;, &#39;black&#39;]<br>  <br>  const containerStyles = {<br>    height: 50,<br>    width: 50,<br>    backgroundColor: `${backgroundColor}`,<br>    color: fontColor,<br>    borderRadius: 10,<br>    margin: 50<br>  };<br><br>  const labelStyles = {<br>    color: fontColor<br>  };<br><br>  return (<br>    &lt;div<br>      style={containerStyles}<br>      onClick={() =&gt; setCardColor(colors[Math.floor(Math.random() * colors.length)])}<br>    &gt;<br>      &lt;span style={labelStyles}&gt;{ title }&lt;/span&gt;<br>    &lt;/div&gt;<br>  );<br>};<br><br>export { Card };</pre><p>Above nothing complicated, we just add 4 things:</p><ul><li>an useState hook to change the backgroundColor of our card</li><li>an array with few differents colors</li><li>we updated the backgroundColor of containerStyle in order to set the value dynamically</li><li>we add onClick listener to change randomly the color of our card.</li></ul><p>Now, click on your card and it should work as expected. But let’s try to extract colors[Math.floor(Math.random() * colors.length)] by adding a small <strong>function</strong> to our package.</p><p>Create src/functions/random.js and add</p><pre>export default function random(colors) { <br>  return colors[Math.floor(Math.random() * colors.length)] <br>}</pre><p>and in our <strong>Card</strong> component</p><pre>import random from ‘../../functions/random’ <br>… <br>onClick={() =&gt; setButtonColor(random(colors))} <br>…</pre><p>And it should work like before ! Now you have one component and one function in your package.</p><p>We will see at the end how to publish it. But before let’s try it in real project by connecting our local package with one of our local project.</p><h3>Connect you local package with an application</h3><p>Once again there is several to do that, I will share the best solution I found for myself so far. I use <a href="https://github.com/whitecolor/yalc"><strong>yalc</strong></a> which will allow you to push on a <strong>local store</strong> all you local packages in order to connect them with projects you want to connect with.</p><p>I’m going to be brief on this section as the <strong>Readme</strong> of Yalc is really friendly.</p><pre><strong>npm i yalc -g</strong> #Install globally yalc<br><strong>yalc publish</strong> #run this cmd in your local package in order to publish the package in your local yalc</pre><p>Before to add you local version to your project you have to remove the current package of your project. Once the package is out you can run the following command:</p><p><strong>yalc add &lt;name-of-package&gt;</strong> it will add your local package in your project and you should see the a .yalc folder</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/476/1*of8sicbxPawN0XMQ_5WiTA.png" /></figure><p>and that’s it ! From this part you should able to import components from your own library.</p><h3>Publish your package</h3><p>Before starting you have to create an <strong>account</strong> on <a href="https://www.npmjs.com/">NPM</a>.</p><p>I want also pointed out that you package-name need to be unique. As you can imagine you have to be really lucky to find an unique name. The better solution is to use a <strong>scoped name</strong>. (eg: @yourusername/package-name) You can checkout the documentation <a href="https://docs.npmjs.com/creating-and-publishing-an-org-scoped-package">here</a>.</p><p>Then you can run</p><pre><strong>npm adduser </strong>#terminal login</pre><pre><strong>npm publish </strong>#or if you are publishing a scoped package, but want it to have a public access, run the command below.</pre><pre><strong>npm publish --access=public</strong></pre><p>Et voila ! You have just published your first package.</p><p>Congrats. 🎉</p><p>Feel free to ask me if you have any questions.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef50b8c91610" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails + RabbitMQ + ActionCable. How to build realtime microservice. (Part 3)]]></title>
            <link>https://medium.com/@clementrollon/rails-rabbitmq-actioncable-how-to-build-realtime-microservice-part-3-dff10522f08?source=rss-b4867967e30b------2</link>
            <guid isPermaLink="false">https://medium.com/p/dff10522f08</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[realtime]]></category>
            <category><![CDATA[actioncable]]></category>
            <dc:creator><![CDATA[Clément Morisset]]></dc:creator>
            <pubDate>Wed, 13 May 2020 14:18:53 GMT</pubDate>
            <atom:updated>2020-05-13T14:21:45.613Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*nGPbvkE8WgxWxegRTPSyAQ.jpeg" /></figure><p>This article is the last one of three.</p><ul><li><a href="https://medium.com/@clementrollon/rails-rabbitmq-actioncable-how-to-build-realtime-microservice-part-1-c25bf00c5187">Part one</a>: we created our <strong>Producer.</strong></li><li><a href="https://medium.com/@clementrollon/rails-rabbitmq-actioncable-how-to-build-realtime-microservice-part-2-23c5f15c3fef">Part two</a>: we created our <strong>Consumer</strong> and we connected both applications together.</li></ul><p>In the third part we are going to see how to display datas in realtime in our Producer by using <strong>websocket</strong> and <strong>ActionCable</strong>.</p><p>Definition of ActionCable according to Rails documentation:</p><blockquote>Action Cable seamlessly integrates <a href="https://en.wikipedia.org/wiki/WebSocket">WebSockets</a> with the rest of your Rails application. It allows for real-time features to be written in Ruby in the same style and form as the rest of your Rails application, while still being performant and scalable</blockquote><p>Perfect, this is exactly what we want.</p><p>First we need to create a channel in order to have a pipeline between client and server. Let’s call it <strong>DatasChannel</strong>.</p><pre># app/channels/datas_channel.rb</pre><pre>class DatasChannel &lt; ApplicationCable::Channel<br>  def subscribed<br>    stream_from &#39;datas&#39;<br>  end<br>end</pre><p>Then in server side we have to <strong>broadcast</strong> the data sent by our <strong>Producer</strong> toward our <strong>DatasChannel</strong>.</p><p>So we can update our <strong>Restaurant</strong> class:</p><pre># app/models/restaurant.rb</pre><pre>class Restaurant<br>  ....</pre><pre>  def self.push(raw_restaurant)<br><strong>    datas = JSON.parse(raw_restaurant)<br>    broadcast_datas(datas)<br></strong>    $redis.lpush(KEY, raw_restaurant)<br>    $redis.ltrim(KEY, 0, STORE_LIMIT-1)<br>  end<br>end</pre><pre>private</pre><pre>def self.broadcast_to_datas(datas)<br>  ActionCable.server.broadcast &#39;datas&#39;,<br>    name: datas[&#39;name&#39;],<br>    city: datas[&#39;city&#39;]<br>end</pre><p>Each time our Restaurant will receive data in server side we will send it towards our client side throughout the <strong>DatasChannel</strong>.</p><p>Now we have to display data in our views. Let’s code some javascript.</p><pre>// app/assets/javascripts/channels/datas.js</pre><pre>App.messages = App.cable.subscriptions.create(&#39;DatasChannel&#39;, {  <br>  received: function(data) {<br>    return $(&#39;#restaurants&#39;).append(this.renderRestaurant(data));<br>  },<br><br>  renderRestaurant: function(data) {<br>    return `&lt;ul&gt;<br>              &lt;li&gt;${data.name}&lt;/li&gt;<br>              &lt;li&gt;${data.city}&lt;/li&gt;<br>            &lt;/ul&gt;`;<br>  }<br>});</pre><p>Our client <strong>subscribes</strong> to our DatasChannel and append data in our views each time that is receiving one.</p><p>But before to see our data displayed we have to add <strong>JQuery</strong>:</p><pre># Gemfile</pre><pre>gem &#39;jquery-rails&#39;</pre><pre># app/assets/javascripts/application.js</pre><pre>//= require jquery<br>//= require jquery_ujs<br>//= require ./channels/datas # we have to load our channel</pre><p>Then, of course just add in your view:</p><pre>&lt;div id=&quot;restaurants&quot;&gt;&lt;/div&gt;</pre><p>That’s it ! 🎉</p><p>From this part as a Restaurant is created in our Crawler you should see in realtime in your Dashboard the restaurant’s informations.</p><p>Before finishing just a quick reminder of what command we need to run in your different app:</p><pre><em># crawler<br></em>redis-server</pre><pre><em># dashboard</em><br>/usr/local/opt/rabbitmq/sbin/rabbitmq-server # run rabbitmq<br>WORKERS=RestaurantsWorker bundle exec rake sneakers:run # run our Sneaker worker to bind queue<br>rails s</pre><p>I hope you enjoyed our little journey throughout microservice and realtime datas. Now if you want to go deeper you can add some ActionCable tests and deploy in production.</p><p>Let me know if you have any questions or issues.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dff10522f08" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails + RabbitMQ + ActionCable. How to build realtime microservice. (Part 2)]]></title>
            <link>https://medium.com/@clementrollon/rails-rabbitmq-actioncable-how-to-build-realtime-microservice-part-2-23c5f15c3fef?source=rss-b4867967e30b------2</link>
            <guid isPermaLink="false">https://medium.com/p/23c5f15c3fef</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[realtime]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Clément Morisset]]></dc:creator>
            <pubDate>Sun, 10 May 2020 18:48:57 GMT</pubDate>
            <atom:updated>2020-07-03T00:41:51.498Z</atom:updated>
            <content:encoded><![CDATA[<p>This is the second part, here we are going to build a <strong>Consumer</strong> to receive the data send by our <strong>Producer</strong>. You can find the first part here.</p><p>Remind the design we are building:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*XkFIThJX3ZOvX646bq0lnA.png" /></figure><p>In this part we are going to create our Dashboard app and our queue (named dashboard.restaurant).</p><p>Ok just run :</p><pre>rails new Dashboard</pre><p>and in you Gemfile add the following gems:</p><pre>gem &#39;redis-rails&#39;                                                   gem &#39;redis-namespace&#39;                                                   gem &#39;sneakers&#39;<br>gem &#39;bunny&#39;</pre><p><a href="https://github.com/redis-store/redis-rails"><strong>Redis</strong></a>: In-memory data structure store, used as a database, cache and message broker. We will use it to backed our Dashboard app.</p><p><a href="https://github.com/resque/redis-namespace"><strong>Redis-Namespace</strong></a>: Redis::Namespace provides an interface to a namespaced subset of your Redis keyspace.</p><p><a href="https://github.com/jondot/sneakers"><strong>Sneakers</strong></a>: A high-performance RabbitMQ background processing framework for Ruby. It made especially for processing messages that come from queues</p><p><a href="https://github.com/ruby-amqp/bunny"><strong>Bunny</strong></a>: Nothing new here, we used it in our Producer.</p><p>First add the Redis initializer below:</p><pre>$redis = Redis::Namespace.new(&quot;dashboard:#{Rails.env}&quot;, redis: Redis.new)</pre><p>First things we need to do is to connect our <strong>Dashboard</strong> (consumer) to our <strong>Crawler</strong> (producer) by creating the <strong>queue</strong> (dashboard.restaurant).</p><pre># app/lib/tasks/rabbitmq.rake</pre><pre>namespace :rabbitmq do<br>  desc &quot;Connect consumer to producer&quot;<br>  task :setup do<br>    require &quot;bunny&quot;</pre><pre>    conn = Bunny.new.tap(&amp;:start)</pre><pre>    ch = conn.create_channel</pre><pre>    queue_restaurants = ch.queue(&quot;dashboard.restaurants&quot;)</pre><pre>    # bind queue to exchange<br>    queue_restaurants.bind(&quot;crawler.restaurants&quot;)</pre><pre>    conn.close<br>  end<br>end</pre><p>Add this rake task to your app. It will allow you to initialize the connection between your two app throughout <strong>RabbitMQ</strong>.</p><p>Then we need to add a restaurant <strong>worker</strong> to handle the message send by the <strong>exchange</strong> that we have created in the first part.</p><pre># app/workers/restaurants_worker.rb</pre><pre>class RestaurantsWorker<br>  include Sneakers::Worker<br><br>  from_queue &quot;dashboard.restaurants&quot;, env: nil</pre><pre>  def work(raw_restaurant)<br>    Restaurant.push(raw_restaurant)<br>    ack! <br>  end<br>end</pre><p>Here we are telling to our worker in what queue It can find the payload. Remember we binded the queue “<strong>dashboard.restaurants</strong>” with the exchange “<strong>crawler.restaurants</strong>”.</p><p>The <strong>work</strong> method allow us to retrieve our data. Then we call a <strong>Restaurant</strong> class (we will create it in a few seconds). The <strong>ack!</strong> keyword means “acknowledge”, it will notify the producer that the message has been received.</p><p>If you run in your console:</p><pre>WORKERS=RestaurantsWorker bundle exec rake sneakers:run</pre><p>you should see</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*v5bVnAQza0HKaDE1sHuV4g.png" /></figure><p>Congrats, now you can hear the Heartbeat of your first Sneaker worker !</p><p>Now we can create our <strong>Restaurant</strong> class we called above. In models folder you can add the following code:</p><pre># app/models/restaurant.rb</pre><pre>class Restaurant<br>  KEY = &quot;restaurant&quot;<br>  STORE_LIMIT = 10</pre><pre>  def self.list(limit = STORE_LIMIT)<br>    $redis.lrange(KEY, 0, limit).map do |raw_restaurant|<br>      JSON.parse(raw_restaurant)<br>    end<br>  end</pre><pre>  def self.push(raw_restaurant)<br>    $redis.lpush(KEY, raw_restaurant)<br>    $redis.ltrim(KEY, 0, STORE_LIMIT-1)<br>  end<br>end</pre><p>Here nothing hard, we have two methods:</p><p><strong>List</strong>: Retrieve and the last 10 items from our Redis db</p><p><strong>Push</strong>: Just push the data (that our RestaurantWorker retrieve from queue) in our Redis.</p><p>From this part, our consumer is connected to our producer and we are able to play with data thanks to Redis.</p><p>Just run all the command below:</p><pre># dashboard cli</pre><pre>redis-server<br>WORKERS=RestaurantsWorker bundle exec rake sneakers:run<br>rake rabbitmq:setup</pre><p>Go on <a href="http://localhost:15672/">http://localhost:15672/</a> and click on Exchange -&gt; crawler.restaurants.</p><p>Then try to create a restaurant in your Crawler app. If everything is configured correctly you should see a beautiful curve in your RabbitMQ UI.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*SGfjyo4KJOSjL-MbWVzK3w.png" /></figure><p>Have you noticed ? Our exchange is <strong>binding</strong> our “dashboard.restaurants” queue. 🎉</p><p>Well, is enough for today. You can try to play with, by displaying the data sent by your producer. If you try you will notice that you have to refresh your browser to get the last data. And it’s not what we want. We want realtime.</p><p>We will see in a third part how to display our restaurant datas in real time with <strong>ActionCable</strong>.</p><p>Third part: <a href="https://medium.com/@clementrollon/rails-rabbitmq-actioncable-how-to-build-realtime-microservice-part-3-dff10522f08">https://medium.com/@clementrollon/rails-rabbitmq-actioncable-how-to-build-realtime-microservice-part-3-dff10522f08</a></p><p>That’s it, let me know if you are facing some issues.</p><p>Cheers.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=23c5f15c3fef" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Rails + RabbitMQ + ActionCable. How to build realtime microservice. (Part 1)]]></title>
            <link>https://medium.com/@clementrollon/rails-rabbitmq-actioncable-how-to-build-realtime-microservice-part-1-c25bf00c5187?source=rss-b4867967e30b------2</link>
            <guid isPermaLink="false">https://medium.com/p/c25bf00c5187</guid>
            <category><![CDATA[microservices]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[rabbitmq]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[actioncable]]></category>
            <dc:creator><![CDATA[Clément Morisset]]></dc:creator>
            <pubDate>Wed, 06 May 2020 21:59:30 GMT</pubDate>
            <atom:updated>2020-07-03T00:40:35.895Z</atom:updated>
            <content:encoded><![CDATA[<h3>Rails + RabbitMQ + ActionCable. How to build realtime microservice. (Part I)</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/1*cBJ9aLGfNelX5qLqRCZhcw.gif" /><figcaption>A rabbit after the last commit of the day</figcaption></figure><h3>Context</h3><p>For few months I am building a crawler to collect restaurant informations and their dishes. The aims is to have as much restaurants as possible in my DB. Have a huge quantity of data is cool but display them is better.</p><p>So I decided to build an app dedicated to display data in real time, and only that. In the context of this article we will name this app <strong>Dashboard</strong>.</p><p>The initial spec is to display charts and datas up to date (means don’t refresh data only once a week/day/hours. We want data updated in real time).</p><p>I have several solution to do this:</p><ul><li><strong>Use HTTP request (API):</strong></li></ul><p>Consume API endpoints each time I go to the dashboard. Quickest and easiest solution. But not efficient, if I have 20 differents charts to display it will make 20 different API calls. And client need to be refresh.</p><ul><li><strong>Use background job (Sidekiq):</strong></li></ul><p>What about us background job to synchronize our datas ? Like run a cron job every ten minutes to fetch data from Crawler DB and populate the Dashboard DB ? Definitely not what I want, what will be the correct recurrency to call our job ? I want a real time updated data, if I run it every ten minutes I take the risk to display fake informations while 10 minutes.</p><ul><li><strong>Use message queue (Advanced Message Queuing Protocol)</strong></li></ul><p>This is the solution I choose. Basically AMQP allow that a producer (our Crawler) notify our consumer (Dashboard) that a new data has been created, in a real time. Once a new data is added in Crawler it will push this data into a dedicated queue that will be received by the consumer. Efficient, timely and single responsability compliant.</p><p><strong>In this first part let’s just configure our producer</strong>, in the second part we will create our consumer (Dashboard). Below the system that we are going to build.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/621/1*XkFIThJX3ZOvX646bq0lnA.png" /></figure><h3><strong>Configure our producer</strong></h3><p>I assume that our Crawler app already exist. Our goal is to push a message in a queue when we create a new restaurant. I’m going to work with <strong>RabbitMQ</strong> and the <strong>Bunny</strong> gem. <a href="https://www.rabbitmq.com/">RabbitMQ</a> is an Open Source message broker/queueing system written in Erlang implementing <a href="http://en.wikipedia.org/wiki/Advanced_Message_Queuing_Protocol">AMQP</a>.</p><p>First I have to install RabbitMQ on my machine, as I am on Mac Os so I run:</p><pre>brew install rabbitmq</pre><p>You can test that it works by running the following command</p><pre>/usr/local/opt/rabbitmq/sbin/rabbitmq-server</pre><p>and go to the admin interface <a href="http://localhost:15672/">http://localhost:15672/</a> . Password and username are « guest » .</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*BR_oeWT0sQytLaqR8silDQ.png" /></figure><p>Perfect. Now we have to add our producer to our app. We are going to use the Bunny gem, a ruby client for RabbitMQ.</p><pre>gem &#39;bunny</pre><p>Then we can create our <strong>Publisher class</strong>.</p><pre>services/publisher.rb</pre><pre>require &#39;bunny&#39;</pre><pre>class Publisher<br>  class &lt;&lt; self<br>    def publish(exchange, message = {})<br>      x = channel.fanout(&quot;crawler.#{exchange}&quot;)<br>      x.publish(message.to_json)<br>    end</pre><pre>    def channel<br>      @channel ||= connection.create_channel<br>    end</pre><pre>    def connection<br>      @connection ||= Bunny.new.tap(&amp;:start)<br>    end<br>  end<br>end</pre><p>Nothing hard here, we instantiate a Bunny instance to start a connection, then we create a channel and we fanout our queue name to this channel. Then we are able to publish our JSON message.</p><p>Just one point about « fanout », according to official RabbitMQ documentation:</p><blockquote>The fanout exchange is very simple. As you can probably guess from the name, it just broadcasts all the messages it receives to all the queues it knows.</blockquote><p>Then we have to call our service and pass our message. As we want to notify our <strong>Consumer</strong> each time that a restaurant is created we are going to call our publish in a <strong>create</strong> callback.</p><pre># frozen_string_literal: true</pre><pre>class Restaurant &lt; ApplicationRecord<br>  after_create { publish_to_dashboard }</pre><pre>  private</pre><pre>  def publish_to_dashboard<br>    Publisher.publish(&#39;restaurants&#39;, attributes)<br>  end<br>end</pre><p>Now you can open you console and create a Restaurant, go to your admin UI and if everything is ok you should see an <strong>Exchange</strong> named « crawler.restaurant ».</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cM3kFvcTKeXj-Jx-yTnKLQ.png" /></figure><p>Congrats. 🎉 You have just created your first exchange. In a second part we will create our <strong>consumer</strong> and add <strong>queue </strong>to connect both applications together.</p><p>Part two: <a href="https://medium.com/@clementrollon/rails-rabbitmq-actioncable-how-to-build-realtime-microservice-part-2-23c5f15c3fef">https://medium.com/@clementrollon/rails-rabbitmq-actioncable-how-to-build-realtime-microservice-part-2-23c5f15c3fef</a></p><p>Let me know if you are facing some issues.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c25bf00c5187" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Comment pousser du code en faisant preuve d’empathie ?]]></title>
            <link>https://medium.com/captive-fr/comment-pousser-du-code-en-faisant-preuve-dempathie-6b5378094168?source=rss-b4867967e30b------2</link>
            <guid isPermaLink="false">https://medium.com/p/6b5378094168</guid>
            <category><![CDATA[team]]></category>
            <category><![CDATA[empathy]]></category>
            <category><![CDATA[commit]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[agile]]></category>
            <dc:creator><![CDATA[Clément Morisset]]></dc:creator>
            <pubDate>Thu, 02 Apr 2020 12:44:16 GMT</pubDate>
            <atom:updated>2020-04-02T14:35:40.795Z</atom:updated>
            <content:encoded><![CDATA[<h3>Comment pousser du code en faisant preuve d’empathie ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*FGEDVx0baxkE0iK2cNUR4A.jpeg" /></figure><p>Il est souvent tentant en tant que développeur de mettre en place des process, des outils, des raccourcis et des bonnes pratiques pour se simplifier la vie. Cependant, même avec les meilleures intentions du monde, il arrive que l’on oublie d’en faire autant pour nos pairs. Ci-dessous vous trouverez trois pistes pour faire de vous le prochain « teammate of the month ».</p><p><strong>I/ Créditez vos pairs.</strong></p><p>À la fin d’un film on peut voir toutes les personnes qui y ont contribué. A la fin d’un concert il est fréquent de remercier les musiciens. Qu’en est-il du pair-programming ?</p><p>Il arrive régulièrement de binômer et généralement les commits n’auront pour seul auteur que le propriétaire de la machine d’où ils ont été poussés. Et Git n’a pas la mémoire courte.</p><p>Heureusement Git nous permet de créditer la personne qui a contribué à l’écriture du code au travers d’un <strong>git-commit-template. </strong>Pour cela vous devez éditer votre fichier <strong>.config</strong> en ajoutant le fichier <strong>git-commit-template </strong>et dedans vous pouvez ajouter les développeurs de votre équipe comme ci-dessous:</p><pre><em># sauter une ligne pour laisser de la place pour vos futurs messages de commit</em><br>#Co-authored-by: Alfredo Doloa &lt;alfredo@oload.fr&gt;<br>#Co-authored-by: Sarah Lupita &lt;lupita@mail.fr&gt;</pre><p>Ensuite vous devez indiquer dans votre fichier <strong>.git-config,</strong> quel template Git doit utiliser lors de vos commits, en ajoutant les lignes ci-dessous:</p><pre>[commit]<br>   template = ~/.config/git-commit-template</pre><p>C’est tout ! Lors de prochain commit tapez <strong>git commit </strong>et vous devriez voir l’écran ci-dessous. Vous n’avez plus qu’à décommenter la ligne de la personne concernée pour la créditer.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*jzEmFVdc9PRr3NR6xgxh_A.png" /></figure><p><strong>II/ Ménagez vos commits.</strong></p><p>Une fois que l’on a ouvert notre pull request, arrive l’étape de la relecture. Cette étape peut être plus ou moins douloureuse pour notre collègue. Un des facteurs aggravants sera la cohérence de nos commits.</p><p>Plus simplement est-ce qu’un commit donné est responsable d’une partie définie de notre code ou bien est-ce qu’une partie définie de notre code est disséminée dans plusieurs commits ?</p><p>Ou encore, avons-nous un commit qui ne fait pas ce qui est indiqué dans son message ? Pire encore un commit qui supprime un focus !? 🤕</p><p>Imaginez-vous inviter un de vos amis dans votre appartement en bazar et en plus lui demander son avis sur votre intérieur ? C’est pareil avec notre branche. Faisons un rapide état des lieux avec le screenshot ci-dessous.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*sOd9NZMB_FjHG1nnp4YUCw.png" /><figcaption>#notinmyname</figcaption></figure><p>Au delà des fautes d’orthographe on peut penser que tout aurait pu tenir en 2 commits. Peut-être même un seul si on avait une meilleure idée de ce qu’il y a derrière cet énigmatique « commit les petites avancées ». C’est plus propre et plus agréable pour nous, mais surtout pour nos collègues.</p><p>Sur le screenshot on aurait dû garder le premier commit « ajout du model prestation_facturé » et faire un</p><pre><strong>git commit --amend --not-edit</strong> <em>#pousse les changements dans le commit précédent sans se poser de question</em></pre><pre><strong>git --push --force-with-lease </strong><em>#permet de mettre à jour votre branche avec les derniers changements</em></pre><p>pour merge les changements qui suivent (renommage et ajout du test) dans notre premier commit. Et simplement un <strong>amend</strong> sur notre dernier commit pour rendre le message plus explicite.</p><p>Volontairement je ne rentre pas dans les détails des commandes Git, vous avez compris le principe. Si vous souhaitez aller plus loin je vous invite à lire <a href="https://about.gitlab.com/blog/2018/06/07/keeping-git-commit-history-clean/">cet article détaillé</a> de Gitlab sur le même sujet.</p><p><strong>III/ Bref, j’ai fait une PR.</strong></p><p>Dans la même lignée que le point précédent il est important pour le bien être de nos collègues d’éviter autant que possible les PR à rallonge et de limiter un ticket à une responsabilité prédéfinie.</p><p>Si je travaille sur l’envoi d’un email lors de l’inscription d’un utilisateur ai-je besoin de ré-organiser le Gemfile dans cette même PR ? Ai-je besoin de corriger une N+1 Query sur l’admin ?</p><p>Même si tous ces changements partent d’une bonne intention ils ont deux principaux effets de bord. Le premier, ils peuvent bloquer votre PR même si l’email de l’inscription (la raison d’être du ticket) est parfaitement exécuté. Le second est de générer du bruit inutile dans la relecture de votre PR.</p><blockquote>Ask a programmer to review 10 lines of code, he’ll find 10 issues. Ask him to do 500 lines and he’ll say it looks good.</blockquote><p>Cette citation explique à elle seule les dangers de réaliser une PR trop grosse, et la démotivation qu’elle peut générer lors de la relecture. Exactement comme une réunion interminable, mal cadrée et sans réel objectif. On commence à penser à autre chose, à décrocher et à vouloir en terminer le plus rapidement possible.</p><p>Une PR concise et précise dans son objectif sera plus attentivement relue et plus propice à une discussion productive. D’où également l’intérêt en amont, de découper les tickets en petits pas pour éviter de passer trop vite sur des sujets importants du fait de la complexité et la longueur de certaines pull request.</p><p>Si vous souhaitez aller plus loin sur cette différence de traitement selon la taille de vos pull request je ne peux que vous encourager à découvrir (ou redécouvrir) l<a href="https://fr.wikipedia.org/wiki/Loi_de_futilit%C3%A9_de_Parkinson">a loi de la futilité de Parkinson </a>et la métaphore du « <a href="http://phk.freebsd.dk/sagas/bikeshed/">Bike Shed</a> » popularisée par Poul-Henning Kamp (ancien membre de la core team FreeBSD)</p><p>Et voilà !</p><p>Si avec ça vous n’arrivez pas à vous faire apprécier par vos collègues développeurs il ne vous reste plus qu’à devenir sympa.</p><p>Clément.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6b5378094168" width="1" height="1" alt=""><hr><p><a href="https://medium.com/captive-fr/comment-pousser-du-code-en-faisant-preuve-dempathie-6b5378094168">Comment pousser du code en faisant preuve d’empathie ?</a> was originally published in <a href="https://medium.com/captive-fr">captive.fr</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Be grateful to your teammate thanks to Git.]]></title>
            <link>https://medium.com/@clementrollon/be-grateful-to-your-teammate-thanks-to-git-f210bc897d68?source=rss-b4867967e30b------2</link>
            <guid isPermaLink="false">https://medium.com/p/f210bc897d68</guid>
            <category><![CDATA[git-commit-template]]></category>
            <category><![CDATA[git]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[team]]></category>
            <category><![CDATA[commit]]></category>
            <dc:creator><![CDATA[Clément Morisset]]></dc:creator>
            <pubDate>Tue, 03 Mar 2020 16:55:11 GMT</pubDate>
            <atom:updated>2020-03-09T20:20:55.801Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/620/1*2BBsihJMc1LSf267eCdIhg.jpeg" /></figure><p>At the end of a movie you can see all the stakeholders that have contributed to it. At the end of a concert is a common thing to thanks all the musicians, stage managers and sound engineers to name a few.</p><p>What about your teammate when you are pushing code ?</p><p>When you do pair-programming, you share more than a screen, you share responsibilities, risks and also a potential standing ovation. But to often you don’t credit your partner of code in your commit. It can be a source of frustration and of demotivation.</p><p>Luckily <strong>Git</strong> is awesome and allow us to co-authored people we work with. Below I will show you how you can get more friendly towards your co-workers with ease.</p><p>The first thing you have to add it’s a <strong>git-commit-template </strong>in your <strong>.config</strong>. For this you can open this file in your editor (me it’s Atom)</p><pre>atom .config</pre><p>add new file names <strong>git-commit-template.</strong></p><p>and in this file you can add all developers you work with, like below:</p><pre>#Co-authored-by: Alfredo Doloa &lt;alfredo@oload.fr&gt;<br>#Co-authored-by: Sarah Lupita &lt;lupita@mail.fr&gt;</pre><p>Great. Then you have to indicate to your git configuration what template use when you commit, for this go to your <strong>.git-config</strong></p><pre>atom .gitconfig</pre><p>and add the lines below:</p><pre>[commit]<br>   template = ~/.config/git-commit-template</pre><p>That’s it !</p><p>Now you are able to co-author your partner by simply typing <strong>git commit</strong> and you should see:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/665/1*GaNMbFElqGoMktTBIOsKvQ.png" /></figure><p>juste uncomment the line you need and push.</p><p>From now you really share responsibilities, risks and success, and this is how a team should looks like. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f210bc897d68" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What I learned by writing gems.]]></title>
            <link>https://medium.com/@clementrollon/what-i-learned-by-writing-gems-62fe2b04e5cf?source=rss-b4867967e30b------2</link>
            <guid isPermaLink="false">https://medium.com/p/62fe2b04e5cf</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[open-source]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[gem]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Clément Morisset]]></dc:creator>
            <pubDate>Thu, 23 Jan 2020 07:35:51 GMT</pubDate>
            <atom:updated>2020-01-23T07:35:51.321Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*TSVTztIKNU11auc51WMiTA.jpeg" /></figure><p>I have been publishing 3 gems for 2 years, of course I didn’t change the game with them. No much stars, no much users..and not really sure to save time/life of many developers.</p><p>But embrace gems development and more widely the open-source is oddly satisfying, each gem taught me something. Below my thoughts that I wanted to share with you.</p><h3>1/ Conchiterz</h3><p>My first gem, I was looking for a small project to publish. Conchiterz is a simply gem to feminize french word/sentence. As many gems are dedicated to english speaker I was guessing that there was a need.</p><h4><em>How to monkey patch </em><strong><em>String</em></strong><em> class method</em></h4><p>I wanted to use my method like a traditional String method like <strong>length </strong>or<strong> </strong><strong>gsub</strong>. So I should monkey patch to get the result below.</p><pre>&lt;%= &#39;Inscrit&#39;.conchiterz(@pratiquant.female?) %&gt;</pre><p>In my main file I have added:</p><pre>module Conchiterz</pre><pre>  module StringMethods    <br>    def conchiterz(switch, escape = [])<br>      Conchiterz.translate(self, switch, escape)<br>    end<br>  end</pre><pre> ....<br> <br>  def monkey_patch(str)    <br>    str.send(:include, Conchiterz::StringMethods)<br>  end<br>end</pre><pre>if defined?(Rails)<br>  Conchiterz.monkey_patch(String)<br>end</pre><p>Feel free to check out my repo</p><p><a href="https://github.com/morissetcl/conchiterz/blob/master/lib/conchiterz.rb#L29">morissetcl/conchiterz</a></p><h3>2/ See Double</h3><p>It’s a small tool CLI, for Rspec Lover, to monitoring your <strong>features</strong> specs and check your duplication. SeeDouble go through all your specs and count the number of occurrence of your «expect» and «result».</p><h4>Create DummyApp engine</h4><p>Sometimes you are building gem that will interact with rails application. In order to test your gem you should had to create a dummy app to simulate a real rails app.</p><p>In my case I had to add dummy app to have a spec folder to count the number of occurrence of «expect» and «result».</p><p>Command to add engine:</p><pre>rails plugin new rails_app — skip-test-unit — dummy-path=spec/dummy</pre><p>These command will generate an engine that looks like a traditional rails app.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/462/1*BLiUYH6FsDIfk9FByOZiag.png" /></figure><p>So I have added fake spec in my dummy app spec:</p><pre>see_double/rails_app/dummy/spec/admin_spec.rb</pre><p>And in my code I have added a statement to find the right spec path</p><pre>def renvoie_le_bon_chemin<br>  Dir.exist?(“./rails_app/dummy”) ? “./rails_app/dummy/spec/**/*.rb” : “./spec/features/**/*.rb”<br> end</pre><p>It turns out that I am not really proud of it but I didn’t try to go in depth so far. Anyway you get the idea.</p><h4>Add an executable</h4><p>What I expected with this gem is to let the user to run the command from the terminal:</p><pre>see_double expect</pre><p>To achieve it I had to add two things. First, I created in my bin folder a bash file with a command I want to run.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YKFgSe46WzdV8zlyIhwcAw.png" /></figure><p>The first line allow you to write ruby in bash file.</p><pre>#!/usr/bin/env ruby -wU</pre><p>Then I add in my <strong>see_double.gemspec</strong>the executable:</p><pre>s.executables &lt;&lt; “see_double”</pre><p>That’s it! Feel free to take a look to my repository.</p><p><a href="https://github.com/morissetcl/see_double">morissetcl/see_double</a></p><h3>3/ Like Im Five</h3><p>The elevator pitch:</p><p>Like Im Five generate a file with factories you need to test a specific object. It use you DB development to retrieve the object you want and all associations you will have need to setup the test.</p><p>The main issue encountered has been to connect gem to user DB development. Indeed the gem need to make multiple requests to find associated object and collect attributes.</p><h4>Connect gem to user database</h4><pre>class GeneralConfiguration<br>  def self.initialize_configuration<br>    config_db = File.read(‘./config/database.yml’)<br>    db_config = YAML.load(ERB.new(config_db).result)<br>        ActiveRecord::Base.establish_connection(db_config[‘development’])<br>  end<br>end</pre><p>The first two lines in the method collect informations from the database.yml of the user. We will use them in the last line to establish a connection with the ActiveRecord database. <a href="https://apidock.com/rails/ActiveRecord/Base/establish_connection/class">More informations here</a>.</p><p>Once we are connected to user DB we can start to make request.</p><h4>Make requests</h4><pre>ActiveRecord::Base.connection.execute(“SELECT * FROM #{table} WHERE id=’#{value}’”).to_a</pre><p>As it was too complicated and overkill to use traditional ActiveRecord query I decided to use raw SQL query by using the connection adaptater. As mentioned in documentation: <em>«Executes the SQL statement in the context of this connection and returns the raw result from the connection adapter.»</em></p><p>This request render a hash object with the raw attributes of the targeted object.</p><p>Feel free to check out my repo to get more informations.</p><p><a href="https://github.com/morissetcl/like_im_five">morissetcl/like_im_five</a></p><h3>Conclusion</h3><p>Participate to open source community is a wonderful experience and a huge source of learning. Building gem is really satisfying and push you to experiment stuff you don’t need to use daily. Everyday you have to use gem in your projects, coding one allow you to have a better understanding of what you use and how you can debug one or even monkey_patching one to get the result you expect. So if you never still experimented this, I encourage you to embrace gem development. Take a small issue you can encounter in your job and start to code a gem to fix it. Learning by doing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62fe2b04e5cf" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 simple tips/stuff to use migrations in a better way.]]></title>
            <link>https://medium.com/@clementrollon/3-simple-tips-stuff-to-use-migrations-in-a-better-way-62152cddf15c?source=rss-b4867967e30b------2</link>
            <guid isPermaLink="false">https://medium.com/p/62152cddf15c</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[tips]]></category>
            <category><![CDATA[migration]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Clément Morisset]]></dc:creator>
            <pubDate>Thu, 26 Dec 2019 10:17:44 GMT</pubDate>
            <atom:updated>2019-12-26T10:39:09.240Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pEar3FplUNqHEjR_lsmwnw.jpeg" /></figure><pre> rails generate migration AddSomethingToSomething<br> rails db:migrate<br> rails db:rollback<br> etc..</pre><p>Are you bored to only use these commands ?</p><p>I have always been frustrated to use migrations daily without trying to make the most of them. In this way I would like share 3 small tips/stuff I found interesting.</p><h3><strong>#1 Test your migrations</strong></h3><p>Sometimes it sounds overkill especially for basic migration, even though it could be useful to test a specific behaviour.</p><p>Let’s take the following migration:</p><pre>class AddIndexClubAndSeasonToPurchaseOrder &lt; ActiveRecord::Migration[5.2]<br>  def up<br>    add_index :purchase_orders,<br>              [:club_id, :season_id],<br>              name: &quot;index_purchase_orders_club_and_season_unique&quot;,<br>              unique: true<br>  end</pre><pre>  def down<br>    remove_index :purchase_orders, [:club_id, :season_id]<br>  end<br>end</pre><p>Here we’re simply adding an scoped index on the purchase_orders table. Testing could be as simple as the code above:</p><pre>require Rails.root.join(&#39;db&#39;, &#39;migrate&#39;, &#39;20191225180138_add_index_club_and_season_to_purchase_order.rb&#39;)</pre><pre>describe AddIndexClubAndSeasonToPurchaseOrder, :migration do<br>  let(:migration) { described_class.new }</pre><pre>  before do<br>    ActiveRecord::Migration.verbose = false<br>    migration.down<br>  end</pre><pre>  it &#39;#up&#39; do<br>    expect(migration.index_exists?(:purchase_orders,[ :club_id, :season_id], name: &#39;index_purchase_orders_club_and_season_unique&#39;)).to be false<br>    migration.up<br>    expect(migration.index_exists?(:purchase_orders,[ :club_id, :season_id], name: &#39;index_purchase_orders_club_and_season_unique&#39;, unique: true)).to be true<br>  end</pre><pre>  it &#39;#down&#39; do<br>    expect(migration.index_exists?(:purchase_orders,[ :club_id, :season_id], name: &#39;index_purchase_orders_club_and_season_unique&#39;)).to be false<br>  end<br>end</pre><p>Several step from top to bottom:</p><ol><li>You need to require your migration file</li><li>Before run your test you can optionnally disable verbose to keep your logs clean and above all you need to rollback the current migration to test it.</li><li>Migrations are just a class with methods. Like up method, you can test it by expecting that your index exist after to have run you migration</li><li>Same things for down !</li></ol><p>If you want to know more about testing migration you absolutely need to check it out the Gitlab repository: <a href="https://gitlab.com/gitlab-org/gitlab-foss/tree/master/spec/migrations">https://gitlab.com/gitlab-org/gitlab-foss/tree/master/spec/migrations</a></p><h3><strong>#2 Use bulk migration</strong></h3><p>Some migrations run on huge table, it can be heavy and slow to execute. In order to avoid this waste of time you can use the bulk option. The following will produce only one (= faster) ALTER TABLE statement:</p><pre>class AddAllUserFields &lt; ActiveRecord::Migration[5.1]<br>  def change<br>    change_table :users, bulk: true do |t|<br>      t.string &quot;nickname&quot;<br>      t.string &quot;personal_email&quot;<br>      t.string &quot;zip_code&quot;<br>      .....<br>      t.text &quot;medical_certificate&quot;<br>      t.text &quot;business_card&quot;<br>      t.boolean &quot;emailing&quot;<br>      t.string &quot;picture_uid&quot;<br>      t.string &quot;country&quot;<br>    end<br>  end<br>end</pre><p><em>Protips: Only supported on the MySQL and PostgreSQL adapter, ignored elsewhere.</em></p><h3><strong>#3 Organize your migrations !</strong></h3><p>Can you imagine a second your app tree without folders ? An ugly blend between controller, model and other service without clear distinction. Why keep a messy migration folder ?</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/460/1*8b8I7HbZuDJQk0CSLdK_7w.png" /></figure><p>Perhaps you have already work on projects with a huge background which means a lot of migrations. You can organize your migration of different manners, the most usually used is the sort by year but I like to sort my migrations like my spec. One folder for one class. So each migration concerning a class/model like User will go in the user folder.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/482/1*awd_hXH0qSbJApoUpOPGTQ.png" /></figure><p>It’s not a big deal and It take your project forward. :)</p><p>That’s it for me. Let me know if you have any question or if you want to share your own tips.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=62152cddf15c" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How easy it is to authenticate users with Firebase and React Native ?]]></title>
            <link>https://medium.com/@clementrollon/how-easy-it-is-to-authenticate-users-with-firebase-and-react-native-b393e5e75769?source=rss-b4867967e30b------2</link>
            <guid isPermaLink="false">https://medium.com/p/b393e5e75769</guid>
            <category><![CDATA[firebase]]></category>
            <category><![CDATA[react-native]]></category>
            <category><![CDATA[authentication]]></category>
            <dc:creator><![CDATA[Clément Morisset]]></dc:creator>
            <pubDate>Mon, 07 Oct 2019 19:24:04 GMT</pubDate>
            <atom:updated>2019-10-07T19:27:21.809Z</atom:updated>
            <content:encoded><![CDATA[<h3>How easy it is to authenticate users with Firebase and React Native ?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*3IpnYxy3cH7HKFKKj278OQ.jpeg" /></figure><p>Thanks for asking !</p><p>Authentication has always been a tricky stuff. Even nowadays with the bunch of libraries, gems or whatever else that can help a developer to build a strong and safe authentication. As a RoR developer I regularly use the popular gem Devise. When I’ve started to develop an app with React Native I wanted to find out an easy/safe solution to achieve it, and my eyes froze to Firebase. A serverless tools which is easy to implement, so let’s go deeper by pluging a React Native app authentication with Firebase with a simple <strong>Login In </strong>form.</p><p><em>Ps: This tutorial assume you’ve already set up your app.</em></p><p>First of all you need to install Firebase in your project as dependency.</p><pre>$ npm i firebase</pre><p>Then we can start to implement our <strong>Connexion</strong> component. Depending of what you need, you should import a bunch of things. For our basic example we are going to import only necessary files.</p><pre><em>#app/components/Connexion.js</em></pre><pre>import React from &#39;react&#39;;<br>import { StyleSheet, Text, View, Alert, TouchableOpacity } from &#39;react-native&#39;;<br>import { Item, Form, Input, Label } from &quot;native-base&quot;;<br>import * as firebase from &quot;firebase&quot;;</pre><p>You surely have noticed that I am importing some UI component from “native-base”, feel free to use one’s you comfortable with.</p><p>From that what we would like to achieve is to connect our app with the Firebase Authentication part. So let’s create a new projet on Firebase.</p><p>So go to Firebase homepage, create an account and your new project. Once it’s ready you should see your dashboard.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QoVaQPt02iyT1r42FhZILA.png" /><figcaption>Worries, I’m french…</figcaption></figure><p>You have to choose how you want to authenticate your user, Firebase offer many ways to do it like Facebook, Github, Twitter, phone, email etc.. For this tutorial we are going to use an email.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*S8r06yZekNhZmiC4zDglvA.png" /></figure><p>Once you’ve chosen email/password you can directly add User in your authentication db throughout the console, but freeze ! Not yet.</p><p>So let’s find out our credentials in settings section, mainly <strong>project ID</strong>, <strong>Api Key </strong>etc..</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fDsawHWVlrT8lNB33P7mtg.png" /></figure><p>Once you get your <strong>credentials</strong> go back to your project and add the following keys in <strong>.env</strong> file.</p><pre><em>#app/.env</em></pre><pre>FIREBASE_API_KEY=your-firebase-project-api-key<br>FIREBASE_AUTH_DOMAIN= your-firebase-project.firebaseapp.com<br>FIREBASE_DB_URL= your-firebase-project-db-url<br>FIREBASE_PROJECT_ID= your-firebase-project-id<br>FIREBASE_STORAGE_BUCKET= your-firebase-project.appspot.com</pre><p>Then you can connect your <strong>environnements variables</strong> with your component by writing down the following code:</p><pre><em>#app/</em>components/Connexion.js</pre><pre>const firebaseConfig = {<br>  apiKey: process.env.FIREBASE_API_KEY,<br>  authDomain: process.env.FIREBASE_AUTH_DOMAIN,<br>  databaseURL: process.env.FIREBASE_DB_URL,<br>  projectId: process.env.FIREBASE_PROJECT_ID<br>};</pre><p>Just below these line you need to initialize Firebase auth component:</p><pre><em>#app/</em>components/Connexion.js</pre><pre>firebase.initializeApp(firebaseConfig);<br>export const auth = firebase.auth();</pre><p>Now we can start by building our <strong>Sign In</strong> form, with no style. I will let you be creative later.</p><pre><em>#app/</em>components/Connexion.js</pre><pre>&lt;Input<br>  autoCapitalize=&quot;none&quot;<br>  autoCorrect={false}<br>  onChangeText={email =&gt; this.setState({ email })}<br>/&gt;</pre><pre>&lt;Input<br>  secureTextEntry={true}<br>  autoCapitalize=&quot;none&quot;<br>  autoCorrect={false}<br>  onChangeText={password =&gt; this.setState({ password })}<br>/&gt;</pre><pre>&lt;TouchableOpacity style={styles.bouton}<br>  onPress={ () =&gt; this.Login(this.state.email, this.state.password) }&gt;<br> &lt;Text style={{ color: &#39;white&#39; }}&gt;<br>  Connexion<br>&lt;/Text&gt;<br>&lt;/TouchableOpacity&gt;</pre><p>As you can see above we are building a very simple form which is going to handle two parameters, <strong>email</strong> and <strong>password</strong>. So we need to add those parameter to our constructor. Go ahead.</p><pre><em>#app/</em>components/Connexion.js</pre><pre>export default class Connexion extends React.Component {<br>  constructor(props) {<br>    super(props);<br>    this.state = {<br>      email: &quot;&quot;,<br>      password: &quot;&quot;,<br>      logged: false<br>    };<br>  }<br>}</pre><p>Nice, but what happen if I press the connexion button ? Good question, quiet nothing I guess.</p><p>We need to implement our <strong>Login</strong> function.</p><pre><em>#app/</em>components/Connexion.js</pre><pre>Login = (email, password) =&gt; {<br>    try {<br>      firebase<br>        .auth()<br>        .signInWithEmailAndPassword(email, password)<br>        .then(() =&gt; this.setState({ logged: true }))<br>        .catch(error =&gt; { alert(&quot;Error : &quot;, error) }<br>        });<br>    } catch (error) {<br>      alert(&quot;Error : &quot;, error);<br>    }<br>  };</pre><p>Awesome, go on your page, fill inputs and press on <strong>Connexion</strong>. If everything goes well you should see an error message on your screen. Mostly, “User does not exist” or something like that. Of course as we did not create users for our app yet.</p><p>From this moment you can choose to go on your Firebase dashboard and add a User manually, or you can stay with me to improve your errors messages. I let you few seconds to think about it.</p><p>…….</p><p>Ok let’s implement better error handling.</p><p>All things we are going to add can be found in Firebase documentation. You can find all <strong>error code</strong> return by Firebase. <a href="https://firebase.google.com/docs/reference/js/firebase.auth.Auth#sign-inwith-credential">https://firebase.google.com/docs/reference/js/firebase.auth.Auth#sign-inwith-credential</a></p><pre><em>#app/</em>components/Connexion.js <br> <br>Login = (email, password) =&gt; {<br>  try {<br>    firebase<br>      .auth()<br>      .signInWithEmailAndPassword(email, password)<br>      .then(() =&gt; this.setState({ logged: true }))<br>      .catch(error =&gt; {<br>        switch (error.code) {<br>          case &#39;auth/wrong-password&#39;:<br>            this.messageErrors(&quot;Veuillez rentrer votre mot de passe&quot;);<br>            break;<br>          case &#39;auth/user-not-found&#39;:<br>            this.messageErrors(&quot;Aucun utilisateur trouvé, veuillez vérifier votre email et votre mot de passe&quot;);<br>            break;<br>          case &#39;auth/invalid-email&#39;:<br>            this.messageErrors(&#39;Le format de votre email est invalide&#39;);<br>            break;<br>          }<br>        });<br>  } catch (error) {<br>    alert(&quot;Error : &quot;, error);<br>  }<br>};</pre><p>That’s it ! You have an authentication form for your existing user. <strong>Sign Up</strong> is not really different, I may do another post about it later.</p><p>But now you can add user from Firebase console and test your authentication. Just be sure to display a different screen when you <strong>logged that </strong>props is set to <strong>true</strong>.</p><p>Let me know if you are facing some issue. :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b393e5e75769" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>