<?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 Matias Carpintini. on Medium]]></title>
        <description><![CDATA[Stories by Matias Carpintini. on Medium]]></description>
        <link>https://medium.com/@carpintinimatias?source=rss-4612a30281d1------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*h_dSuldDnlVKmKeF4QSLYQ.jpeg</url>
            <title>Stories by Matias Carpintini. on Medium</title>
            <link>https://medium.com/@carpintinimatias?source=rss-4612a30281d1------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Thu, 03 Dec 2026 09:41:20 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@carpintinimatias/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[How to generate OG links preview like Dev.to (for free) with Rails 7]]></title>
            <link>https://carpintinimatias.medium.com/how-to-generate-og-links-preview-like-dev-to-for-free-with-rails-7-14b034c57f5?source=rss-4612a30281d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/14b034c57f5</guid>
            <category><![CDATA[open-graph]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Matias Carpintini.]]></dc:creator>
            <pubDate>Sat, 04 Jun 2022 13:58:36 GMT</pubDate>
            <atom:updated>2022-06-04T13:58:36.564Z</atom:updated>
            <content:encoded><![CDATA[<p>Hey hey heyyyyyy<br>Quick article on how to have beauty link previews, just like Dev.to does</p><p>You’re gonna get something like this:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*CTYqNI1QZr_HfAVG.png" /></figure><p>Yup, was being literal with the “<em>like dev.to</em>” 😛</p><p>Almost every guide that i found was using <a href="https://htmlcsstoimage.com/">htmlcsstoimage.com</a>, in fact, dev.to uses it. It’s pretty popular, and efficient, BUT, i don’t want to pay $14 bucks for each 1k images 😂🐁</p><p>So, i’m going to use <a href="https://github.com/Studiosity/grover">Grover</a>: A Ruby gem to transform HTML into PDFs, PNGs or JPEGs using Google Puppeteer and Chromium.</p><p>If you want to build this with, let’s say, Node.js, you can also follow me. Puppeteer is popular and easy to use.</p><p><strong>Long story short:</strong> We’re going to build a HTML view and take an screenshot of it.</p><p>You can create a blank Rails project, or just add additional functionality to your current app.</p><h3>Setup</h3><p>Install Grover gem with<br>bundle add grover</p><p>And the dependency of Grover, <em>Puppeteer</em>, with:<br>yarn add puppeteer</p><p>Then create an empty controller where you can respond with different link preview templates:<br>rails g controller og-imager dev_to</p><p>In the dev_to action, let&#39;s call Grover and let him do the magic<br>app/controllers/og_imager_controller.rb</p><pre>class OgImagerController &lt; ApplicationController<br>  # GET /og_imager/dev_to<br>  # @param {string} title<br>  # @param {string} avatar<br>  # @param {string} username<br>  # @param {string} timestamp<br>  # @param {array} logos<br>  # @returns image/png<br>  def dev_to<br>    # Get params and set to variable<br>    # TODO: Retrieve your object instead :p<br>    @title = params[:title]<br>    @avatar = params[:avatar]<br>    @username = params[:username]<br>    @timestamp = params[:timestamp]<br>    @logos = params[:logos]</pre><pre>    # Grover.new accepts a URL or inline HTML and optional parameters for Puppeteer<br>    grover = Grover.new(<br>      render_to_string<br>    )</pre><pre>    # Get a screenshot<br>    png = grover.to_png</pre><pre>    # Render image<br>    send_data(png, type: &#39;image/png&#39;, disposition: &#39;inline&#39;)<br>  end<br>end</pre><p>Here’s our view, just simple HTML/CSS<br>app/views/og_imager/dev_to.html.erb</p><pre>&lt;div class=&quot;container&quot;&gt;<br>  &lt;div class=&quot;card&quot;&gt;<br>    &lt;h1 class=&quot;title&quot;&gt;<br>      &lt;%= @title %&gt;<br>    &lt;/h1&gt;<br>    &lt;div class=&quot;details&quot;&gt;<br>      &lt;div class=&quot;user&quot;&gt;<br>        &lt;img src=&quot;&lt;%= @avatar %&gt;&quot; class=&quot;avatar&quot;&gt;<br>        &lt;p class=&quot;username&quot;&gt;<br>          &lt;%= @username %&gt; - &lt;%= @timestamp %&gt;<br>        &lt;/p&gt;<br>      &lt;/div&gt;<br>      &lt;div class=&quot;logos&quot;&gt;<br>        &lt;% @logos.each do |logo| %&gt;<br>          &lt;img src=&quot;&lt;%= logo %&gt;&quot; class=&quot;logo&quot;&gt;<br>        &lt;% end %&gt;<br>      &lt;/div&gt;<br>    &lt;/div&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><pre>&lt;style&gt;<br>  @import url(https://medium.com/&#39;https://fonts.googleapis.com/css2?family=Roboto:wght@400;500&amp;display=swap&#39;);</pre><pre>  *{<br>    font-family: &#39;Roboto&#39;, sans-serif;<br>    color: #cd685f;<br>  }</pre><pre>  .container{<br>    width: 1128px;<br>    height: 600px;<br>    display: flex;<br>  }</pre><pre>  .card{<br>    display: flex;<br>    justify-content: space-between;<br>    flex-direction: column;<br>    margin: 2.8rem 4rem 4rem 2.8rem;<br>    border: 3px solid #c56b61;<br>    border-radius: 25px 25px 0px 0px;<br>    box-shadow: 7px 10px 0px 1px #c56b61;<br>    padding: 3.8rem 1.8rem 1.8rem 1.8rem;<br>  }</pre><pre>  .title{<br>    margin: 0px;<br>    font-weight: 500;<br>    font-size: 5rem;<br>    line-height: 80px;<br>  }</pre><pre>  .details{<br>    display: flex;<br>    justify-content: space-between;<br>  }</pre><pre>  .user{<br>    display: flex;<br>    align-items: center;<br>  }</pre><pre>  .avatar{<br>    border: 3px solid #c56b61;<br>    width: 50px;<br>    height: 50px;<br>    border-radius: 50%;<br>    margin-right: 10px;<br>  }</pre><pre>  .username{<br>    margin: 0;<br>    font-size: 2.5rem;<br>  }</pre><pre>  .logos{<br>    display: flex;<br>    justify-content: space-between;<br>  }</pre><pre>  .logo{<br>    width: 60px;<br>    height: 60px;<br>    margin-left: 20px;<br>    transform: rotate(5deg);<br>  }<br>&lt;/style&gt;</pre><p>And finally, create an initializer to set our Browser viewport (final image size).</p><p>initializers/grover.rb</p><pre>Grover.configure do |config|<br>  config.options = {<br>    viewport: {<br>      width: 1128,<br>      height: 600<br>    },<br>  }<br>end</pre><p>If you have created a blank project, and want to use this as a micro-service, here’s a guide on how to deploy this thing to Heroku.</p><ol><li>Create the app on your Heroku account (T’m assuming you already have the cli installed): heroku create your_app_name</li><li>Warn Heroku of our JS library (Puppeteer): heroku buildpacks:add heroku/nodejs --index=1</li><li>And also help him to setup Puppeteer dependencies 😛: heroku buildpacks:add jontewks/puppeteer --index=2</li><li>Tell Grover to run Puppeteer in the “no-sandbox”: heroku config:set GROVER_NO_SANDBOX=true</li></ol><p>To make use of this image on the link preview, you will need <a href="https://ogp.me/">The Open Graph protocol</a>. Just simple meta tags that browsers will look for.</p><p>Meta tags are always on</p><p>so,<br>app/views/layouts/application.html.erb</p><pre>&lt;%= yield(:head) %&gt;</pre><p>And then ask ERB to fill previous block with</p><pre>&lt;%= content_for :head do %&gt;<br>  &lt;meta property=&quot;og:title&quot; content=&quot;&lt;%= @article.title %&gt;&quot;&gt;<br>  &lt;meta property=&quot;og:image&quot; content=&quot;&lt;%= article_link_preview(@article) %&gt;&quot;&gt;<br>  &lt;meta property=&quot;og:image:type&quot; content=&quot;image/png&quot; /&gt;<br>  &lt;meta property=&quot;og:image:width&quot; content=&quot;1128&quot;&gt;<br>  &lt;meta property=&quot;og:image:height&quot; content=&quot;600&quot;&gt;<br>  &lt;meta name=&quot;twitter:card&quot; content=&quot;summary_large_image&quot; /&gt;<br>&lt;% end %&gt;</pre><p>at your details view. Like: /articles/:id</p><p>The twitter:card thing it&#39;s because they are more fancy on link previews, you can read more about that <a href="https://developer.twitter.com/en/docs/twitter-for-websites/cards/overview/markup">here</a></p><p>The previous article_link_preview method it&#39;s a simple helper that generates the URL that we are looking for.</p><p>app/helpers/articles_helper.rb</p><pre>def article_link_preview article<br>  uri = URI.parse(&#39;https://your_app_name.herokuapp.com/ogimage&#39;)<br>  uri.query = URI.encode_www_form(<br>    title: article.title,<br>    &#39;images[]&#39;: article.tags.collect(&amp;:image),<br>    timestamp: article.created_at.to_formatted_s(:short),<br>    ...<br>  )<br>  uri.to_s<br>end</pre><p>You will get something like this:<br>https://your_app_name.herokuapp.com/og_imager/dev_to?title=Real%20Time%20Notification%20System%20with%20Hotwire,%20in%20Rails%207&amp;avatar=https://dev-to-uploads.s3.amazonaws.com/uploads/user/profile_image/369241/a0111bcb-a046-4398-98cd-f4cf0e2f8d0d.png&amp;username=Matias%20Carpintini&amp;timestamp=13%20April&amp;logos[]=https://img.icons8.com/office/80/000000/ruby-gemstone.png&amp;logos[]=https://practicaldev-herokuapp-com.freetls.fastly.net/assets/devlogo-pwa-512.png</p><p>Here’s the <a href="https://github.com/matias-carpintini/og-imager">repo</a> of the whole thing.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14b034c57f5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real Time Notification System with Hotwire, in Rails 7]]></title>
            <link>https://carpintinimatias.medium.com/real-time-notification-system-with-hotwire-in-rails-7-14de2570a0b9?source=rss-4612a30281d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/14de2570a0b9</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[notifications]]></category>
            <dc:creator><![CDATA[Matias Carpintini.]]></dc:creator>
            <pubDate>Sat, 04 Jun 2022 13:56:18 GMT</pubDate>
            <atom:updated>2022-06-04T13:56:18.548Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>DISCLAIMER</strong><br>Time ago i wrote an article here, on how to build a notifications system with Rails and Redis, from scratch. This new one it’s a quick update of that one.</p><p>If you don’t know what i’m talking about, and are curious on how to accomplish same thing without Hotwire, here you go: <a href="https://dev.to/matiascarpintini/real-time-notification-system-with-sidekiq-redis-and-devise-in-rails-6-33l9">Real Time Notification System with Sidekiq, Redis and Devise in Rails 6</a></p><p>Rails 7 was a huuuge update. I’m not going to talk about that in this post but Hotwire. <a href="https://hotwire.dev/">Hotwire</a> became -officially- part of Rails 7. Now you can have real-time interactions, SPA looking Rails projects, without even write a single line of JS.</p><p><strong>TL;TR</strong><br>Hotwire can be understood as an umbrella/approach. Inside this thing you will find 2 little boys, Turbo, that replaces TurboLinks, and Stimulus, which is in their own words: <em>A modest JavaScript framework for the HTML you already have</em> or, the thing that we’re going to use when we need to listen some button clicks :p</p><h3>Hands on 👊</h3><p>I’m going to use a clean project, you can <a href="https://dev.to/matiascarpintini/real-time-notification-system-with-hotwire-in-rails-7-1j9f#how-to-notifications">skip this</a> if you want. Therefore:<br>$ rails new notifications_with_hotwire -d=postgresql -T</p><p>???<br>-d=postgresql specify the DB that we&#39;re going to use. By default, Rails uses sqlite3.</p><p>-T skips test files.</p><p>To make it more real, let’s include <a href="https://github.com/heartcombo/devise">Devise</a>, and <a href="https://github.com/rails/tailwindcss-rails">Tailwind</a> with their icons library, <a href="https://github.com/bharget/heroicon">Heroicons</a>:</p><p>$ bundle add devise tailwindcss-rails heroicon</p><p><em>Now we need to setup that gems…</em><br>For tailwind and heroicons just run $ rails tailwindcss:install &amp;&amp; rails g heroicon:install</p><p>For Devise, run $ rails g devise:install &amp;&amp; rails g devise User and follow their notes.</p><p>I’m also going to create a resource that will dispatch notifications later on: $ rails g scaffold Post title body:rich_text user:references. Don&#39;t forget to assign user on create,</p><pre>before_action :authenticate_user!, except: [ :index, :show ]<br>def create<br>  @post = current_user.posts.new(post_params)<br>  ....</pre><p>And of course, specify the relationship on the User model with:</p><pre>has_many :posts</pre><p>Finally, let’s move to what you’re looking for 😉</p><h3>How to notifications</h3><p>I want to create notifications for different resources, such as posts, comments or likes. For this, i’m using a polymorphic reference. If you’re not familiar with, read about that <a href="https://guides.rubyonrails.org/association_basics.html#polymorphic-associations">here</a>.</p><p>$ rails g model Notification item:references{polymorphic} user:references viewed:boolean</p><p>Just add a default value for viewed field on the migration:</p><pre>t.boolean :viewed, null: false, default: false</pre><p>Build a basic nav and place the notifications count badge on it with something like:</p><pre>&lt;%= link_to notifications_path, class: &quot;bg-gray-800 p-1 rounded-full text-gray-400 hover:text-white focus:outline-none focus:ring-2 focus:ring-offset-2 focus:ring-offset-gray-800 focus:ring-white&quot; do %&gt;<br>  &lt;span class=&quot;sr-only&quot;&gt;View notifications&lt;/span&gt;<br>  &lt;%= heroicon &quot;bell&quot;, variant: :outline, options: { class: &quot;h-6 w-6&quot; } %&gt;<br>  &lt;%= tag.div id: :notifications_count do %&gt;<br>    &lt;%= render &quot;notifications/count&quot;, count: current_user.unviewed_notifications_count %&gt;<br>  &lt;% end %&gt;<br>&lt;% end %&gt;</pre><p>You may noticed that unviewed_notifications_count doesn’t exists on our User model so, let’s define that as a class method<br>on user.rb:</p><pre>has_many :notifications<br>def unviewed_notifications_count<br>  self.notifications.unviewed.count<br>end</pre><p>And the app/views/notifications/_count partial is needed for Turbo. Going to explain this below.</p><pre>&lt;%= tag.div id: :notifications_count do %&gt;<br>  &lt;% if count &gt; 0 %&gt;<br>    &lt;span class=&quot;h-6 w-6 flex items-center justify-center bg-red-500 rounded-md text-sm&quot;&gt;<br>      &lt;%= count &gt; 9 ? &quot;+9&quot; : count  %&gt;<br>    &lt;/span&gt;<br>  &lt;% end %&gt;<br>&lt;% end %&gt;</pre><p>Here’s the thing of the whole article (notification.rb). Turbo actions. Let&#39;s take the first callback to explain what&#39;s going on.</p><ol><li><em>broadcast</em>: now turbo handle the sttuff we built on the <a href="https://dev.to/matiascarpintini/real-time-notification-system-with-sidekiq-redis-and-devise-in-rails-6-33l9">previous article</a>. TD;TR: ApplicationCable to stablish connection between the user and the server, create and send jobs to the background to be performed async with Redis.</li><li><em>prepend/replace/remove</em>: simple JS actions</li><li><em>to</em>: the target (AKA <a href="https://turbo.hotwired.dev/handbook/streams">stream</a>). In this case, i’m establishing connection with the specific signed user.</li><li><em>target</em>: simple HTML (or <a href="https://turbo.hotwired.dev/handbook/frames">turbo_frame</a>) element used to perform the JS action.</li></ol><pre>scope :unviewed, -&gt;{ where(viewed: false) }<br>default_scope { latest }</pre><pre>after_create_commit do <br>  broadcast_prepend_to &quot;broadcast_to_user_#{self.user_id}&quot;, <br>    target: :notifications<br>end</pre><pre>after_update_commit do <br>  broadcast_replace_to &quot;broadcast_to_user_#{self.user_id}&quot;, <br>    target: self<br>end</pre><pre>after_destroy_commit do <br>  broadcast_remove_to &quot;broadcast_to_user_#{self.user_id}&quot;, <br>    target: :notifications<br>end</pre><pre>after_commit do<br>  broadcast_replace_to &quot;broadcast_to_user_#{self.user_id}&quot;, <br>    target: &quot;notifications_count&quot;, <br>    partial: &quot;notifications/count&quot;, <br>    locals: { count: self.user.unviewed_notifications_count }<br>  end<br>end</pre><p>Yup, the <em>latest</em> scope didn’t exists either, i like to define that on application_record.rb.</p><pre>scope :latest, -&gt;{ order(&quot;created_at DESC&quot;) }</pre><p>In application.html.erb create the stream that allows the previous snippet &quot;talk&quot; with the signed user (without this everyone&#39;s getting everyone&#39;s notifications 😛)</p><pre>&lt;% if user_signed_in? %&gt;<br>  &lt;%= turbo_stream_from dom_id(current_user, :broadcast_to) %&gt;<br>&lt;% end %&gt;</pre><p>Now let’s put notifications-related stuff on concerns/notificable.rb.</p><ol><li><em>included</em> will append where we import this concern. It sets a relationship and have a simple callback that runs once we <em>create</em> a new resource (post in this case) object.</li><li>If that resource model have the user_ids method, it will create the notifications for that users.</li></ol><pre>module Notificable<br>  extend ActiveSupport::Concern</pre><pre>  included do<br>    has_many :notifications, as: :item, dependent: :destroy<br>    after_create_commit :send_notifications_to_users<br>  end</pre><pre>  def send_notifications_to_users<br>    if self.respond_to? :user_ids<br>      self.user_ids&amp;.each do |user_id|<br>        Notification.create user_id: user_id, item: self<br>      end<br>    end<br>  end<br>end</pre><p>So then, when we want to create notifications for a new resource, we just need to include that concern on our resource model, in this case post.rb</p><pre>include Notificable</pre><pre>def user_ids<br>  User.where.not(id: self.user_id).ids<br>end</pre><p>Finally, to show the notifications on our application UI, let’s respond to /notifications path on notifications_controller.rb</p><pre>class NotificationsController &lt; ApplicationController<br>  before_action :authenticate_user!</pre><pre>  def index<br>    @notifications = current_user.notifications<br>    @notifications.update(viewed: true)<br>  end<br>end</pre><p>Don’t forget to notify the controller about this new path on config/routes.rb</p><pre>resources :notifications, only: [ :index ]</pre><p>And there you go. The notifications index :)<br>views/notifications/index.html.erb</p><pre>&lt;div class=&quot;space-y-4&quot;&gt;<br>  &lt;p class=&quot;text-lg leading-6 font-medium text-gray-900 flex justify-between&quot;&gt;<br>    Notifications<br>  &lt;/p&gt;<br>  &lt;ul class=&quot;border-t border-b border-gray-200 divide-y divide-gray-200&quot; id=&quot;notifications&quot;&gt;<br>    &lt;%= render @notifications %&gt;<br>  &lt;/ul&gt;<br>&lt;/div&gt;</pre><p>The previous render @notifications will look for the views/notifications/_notification.html.erb partial.<br>And i like to render a new partial here, since we have a polymorphic relation.</p><pre>&lt;li class=&quot;py-4&quot; id=&quot;&lt;%= dom_id(notification) %&gt;&quot;&gt;<br>  &lt;%= render &quot;notifications/#{notification.item_type.downcase}&quot;, notification: notification %&gt;<br>&lt;/li&gt;</pre><p>That previous render will look for views/notifications/_post.html.erb (in this case). If you create notifications for, let&#39;s say, likes then you need to create a new partial, called _like. And customize the notification for that new resource.</p><pre>&lt;p class=&quot;text-gray-900&quot;&gt;<br>  &lt;%= notification.item.user.email %&gt; just posted:<br>  &lt;%= link_to notification.item.title, notification.item, class: &quot;underline font-medium&quot; %&gt;<br>&lt;/p&gt;</pre><p>Here’s the <a href="https://github.com/matias-carpintini/notifications-with-hotwire">repo</a> with everything :)</p><p>Bye.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=14de2570a0b9" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Spam filtering system — Bayes classifier]]></title>
            <link>https://carpintinimatias.medium.com/spam-filtering-system-bayes-classifier-dbff7a8804ac?source=rss-4612a30281d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/dbff7a8804ac</guid>
            <category><![CDATA[machine-learning]]></category>
            <category><![CDATA[spam]]></category>
            <category><![CDATA[rails]]></category>
            <dc:creator><![CDATA[Matias Carpintini.]]></dc:creator>
            <pubDate>Sat, 04 Jun 2022 13:52:45 GMT</pubDate>
            <atom:updated>2022-06-04T13:52:45.857Z</atom:updated>
            <content:encoded><![CDATA[<h3>Spam filtering system — Bayes classifier</h3><h4>What the f*ck is a Bayes Cassifier?</h4><h3>The Bayes Rule, “The theory that never died”</h3><p>A simple 17th century theory for the evaluation of knowledge, criticized for most of the 20th century.</p><p>It helps people evaluate their initial ideas, update and modify them with new information, in order to make better decisions.</p><blockquote><em>Initial beliefs + recent objective data = A new improved belief.</em></blockquote><p>The theory is very robust. In practice, Bayes rule requires multiple calculations, and powerful computers that reintegrate millions of times the probability of an initial belief each time new information arrives. Bayes rule does not generate an absolutely true (exact answer), instead, it uses probability to move step by step toward the most likely conclusion.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*-lxy9x5dWujxyBJKwlcWBw.jpeg" /><figcaption>Thomas Bayes</figcaption></figure><p>It was discovered and published by two clergymen and amateur mathematicians, the Englishman Thomas Bayes and his Welsh friend Richard Price, during the 18th century.</p><p>The French mathematician Pierre-Simon Laplace developed it in the form in which it is used today. Now we could call it the Bayes-Price-Laplace theory, or GLP for short.</p><p>Part of the initial controversy is due to the fact that during the 40’s of the 18th century a harsh controversy had opened about the improbability of Christian miracles. The question was whether there was evidence in the natural world that would help us reach rational conclusions about God the creator, which in the 18th century was known as “the cause” or “the first cause”.</p><p>We do not know if Bayes was trying to prove the existence of God as a cause. But we do know that he tried to deal mathematically with the problem of cause and effect;</p><p>During the Cold War, the United States Air Force lost a hydrogen bomb off the coast of Palomares, and the United States Navy began to secretly develop the Bayesian theory for finding underwater objects.</p><p>In 2009, Air France Flight 447 disappeared in the South Atlantic Ocean with 228 people on board. The United States Navy had developed Bayesian search theory enough to end two years of unsuccessful search for AF447 in a week’s underwater search.</p><p>Today we use it for an immense amount of things, such as filtering spam and training autopilot systems.</p><p>If you want to know more about the history behind it, take a look to <a href="https://www.youtube.com/watch?v=BcvLAw-JRss">this video</a>.</p><h4>Ok, nice. But you haven’t answered the previous question!</h4><h3>Naive Bayes Classification</h3><p>The Naive Bayes classifier is a machine learning technique that can be used to classify objects such as text documents into two or more classes. A new object it’s classified by the similarity between others.</p><p>Despite its “naivete”, the naive Bayes method tends to work very well in practice.</p><blockquote><em>“all models are wrong, but some are useful” — George Box</em></blockquote><h4>Cool, go for it!</h4><p>So, for our purpose (spam filtering), we need data (a lot of emails), classify each email as spam or ham (legitimate) and then analyze the words independently, in order to get the most common words in each of those classes.</p><p>P.S: You can have many classes as you want. Like Gmail does with Promotions, Updates, Forums or Social.</p><p><em>Initial beliefs:</em> For simplicity, let says that the half of emails we get are spam. 1:1.</p><p>Now we need to obtain the probability that each of those words appears in spam or ham. The simplest way is to count how many times each word appears in the data and divide the number by the total word count.</p><pre>+-----------+--------------------+---------------+<br>|   word    |       spam         |     ham       |<br>+-----------+--------------------+---------------+<br>| Free      | 184                | 12            |<br>| total     | 104342             | 294554        |<br>+-----------+--------------------+---------------+</pre><p>In this example, the probability that the word “Free” in a spam message appears is 1 out of 567 words. Same exercise for ham: 1 in 24</p><p><strong>Recent objective data:</strong> If we found the word “Free” in our message, it will increase the probability of being spam in 23.6 (567/24)</p><p>1/1 (initial beliefs: half messages we receive are spam) * 23.6 (we just found the world “Free” in our email) = 23.6.</p><p>There are on the average about 23.6 spam messages for each ham message, or to use whole numbers, 236 (23.6*10) spam messages for every 10 ham messages. So, the probability would be: 236 / (236 + 10) * 100 = 95.9%</p><p>To handle the rest of the words in a email, we can use exactly the same procedure. The posterior odds after one word (what we just calculated), will become the prior odds (or the <em>initial belief</em>) for the next word, and so on.</p><p>You may have noticed that how whole thing will be biased. Since once we are going to analyze the second word, it already have a strong belief that the email is spam, due it has the free world on it, and same with next words.</p><p>That’s known as the base rate fallacy, and you can read more about <a href="https://en.wikipedia.org/wiki/Base_rate_fallacy">here</a>.</p><p>But let’s keep it simple,</p><blockquote><em>“Land-and-Expand”</em></blockquote><h3>How can i play with this?</h3><p>I just found <a href="https://github.com/jekyll/classifier-reborn/">classifier-reborn</a>, a gem that keeps it pretty simple. And <a href="https://www.kaggle.com/datasets/venky73/spam-mails-dataset">this</a> dataset.</p><p>Here you go:</p><pre>require &#39;classifier-reborn&#39;<br>require &#39;csv&#39;</pre><pre># Load dataset<br>dataset = CSV.parse(File.read(&quot;spam_ham_dataset.csv&quot;), headers: true)</pre><pre># Create our Bayes / LSI classifier<br>classifier = ClassifierReborn::Bayes.new(&#39;Spam&#39;, &#39;Ham&#39;)</pre><pre># Train the classifier<br>dataset[1..-1].each_with_index do |email, index|<br>  if dataset[index][&quot;label&quot;] == &quot;spam&quot;<br>    classifier.train &quot;Spam&quot;, dataset[index][&quot;text&quot;]<br>  else<br>    classifier.train &quot;Ham&quot;, dataset[index][&quot;text&quot;]<br>  end<br>end</pre><pre># Play with it<br>puts &quot;Insert your email here (txt)&quot;<br>puts classifier.classify gets</pre><p>You can also check <a href="https://github.com/sausheong/naive-bayes">this repo</a>, to see how it looks without the gem :p</p><p>Bye.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dbff7a8804ac" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to SignIn with an Email — Ruby on Rails and Devise]]></title>
            <link>https://carpintinimatias.medium.com/how-to-signin-with-an-email-ruby-on-rails-and-devise-582b73ac58ed?source=rss-4612a30281d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/582b73ac58ed</guid>
            <category><![CDATA[authentication]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Matias Carpintini.]]></dc:creator>
            <pubDate>Mon, 28 Sep 2020 02:03:45 GMT</pubDate>
            <atom:updated>2020-09-28T02:09:25.567Z</atom:updated>
            <content:encoded><![CDATA[<h3>How to SignIn with an Email — Ruby on Rails and Devise</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*oSlZ3WLbSQ9R6I2grolKbw.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@hostreviews?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Stephen Phillips — Hostreviews.co.uk</a> on <a href="https://unsplash.com/s/photos/gmail?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Passwords are a problem for users. A good practice to skip this is by sending an access link to your account by email, that link has a token that we will use to validate and finally, sign in to the user to their account. Next, I’m going to show you an implementation in Ruby On Rails 6 with Devise.</p><p><strong>NOTE</strong>: I am going to create an application from 0 for avoid mistakes.</p><h3>Setting up</h3><p>Create the project: $ rails new magicLinks -T --skip-turbokinks --database=postgresql</p><h4>Installing dependencies…</h4><p>Add this to your Gemfile.rb</p><pre>gem &#39;devise&#39;, &#39;~&gt; 4.7&#39;, &#39;&gt;= 4.7.1&#39;<br>group :development, :test do<br>  gem &#39;letter_opener&#39;, &#39;~&gt; 1.7&#39; // For open emails in the browser<br>end</pre><p>Then, $ bundle install<br><strong>Let&#39;s install Devise:</strong> with $ rails g devise:install &amp;&amp; rails g devise User &amp;&amp; rails db:create &amp;&amp; rails db:migrate</p><pre>config.action_mailer.default_url_options = { host: &#39;localhost&#39;, port: 3000 }<br>config.action_mailer.delivery_method = :letter_opener</pre><p>Devise asks us for a root path, let’s do that: $ rails g controller welcome index.<br>Add this in your app/config/routes.rb:</p><pre>root &#39;welcome#index&#39;</pre><h3>Let’s do it 👊</h3><p>First, we need to create a table for save the generated tokens on our db.<br>So, $ rails g model EmailLink token expires_at:datetime user:references &amp;&amp; rails db:migrate</p><p>Now we are going to generate the token and send the email when this happens, for that, in app/models/email_link.rb:</p><pre>class EmailLink &lt; ApplicationRecord<br>  belongs_to :user<br>  after_create :send_mail</pre><pre>  def self.generate(email)<br>    user = User.find_by(email: email)<br>    return nil if !user</pre><pre>    create(user: user, expires_at: Date.today + 1.day, token: generate_token)<br>  end</pre><pre>  def self.generate_token<br>    Devise.friendly_token.first(16)<br>  end</pre><pre>  private<br>  def send_mail<br>    EmailLinkMailer.sign_in_mail(self).deliver_now<br>  end<br>end</pre><p>Let’s generate the controller to trigger the previous callback when the user gives us their email and sends the form, rails g controller EmailLinks new create.</p><p>Let’s add the necessary routes in our app/config/routes.rb.</p><pre>root &#39;welcome#index&#39;<br>get &#39;email_links/new&#39;, as: :new_magic_link<br>post &#39;email_links/create&#39;, as: :magic_link<br>get &#39;email_links/validate&#39;, as: :email_link</pre><p>Now, let’s give functionality to our controller:</p><pre>class EmailLinksController &lt; ApplicationController<br>  def new</pre><pre>  end</pre><pre>  def create<br>    @email_link = EmailLink.generate(params[:email])</pre><pre>    if @email_link<br>      flash[:notice] = &quot;Email sent! Please, check your inbox.&quot;<br>      redirect_to root_path<br>    else<br>      flash[:alert] = &quot;There was an error, please try again!&quot;<br>      redirect_to new_magic_link_path<br>    end<br>  end</pre><pre>  def validate<br>    email_link = EmailLink.where(token: params[:token]).where(&quot;expires_at &gt; ?&quot;, DateTime.now).first</pre><pre>    unless email_link<br>      flash[:alert] = &quot;Invalid or expired token!&quot;<br>      redirect_to new_magic_link_path<br>    end</pre><pre>    sign_in(email_link.user, scope: :user)<br>    redirect_to root_path<br>  end<br>end</pre><p>At this point, our program is capable of generating the token, validating it and logging in. What we have left is to send the email and the view where the user gives us their email.</p><p><strong>NOTE</strong>: If you want to see these alerts, you must add them in app/views/layouts/application.html.erb, inside the body tag:</p><pre>&lt;p class=&quot;notice&quot;&gt;&lt;%= notice %&gt;&lt;/p&gt;<br>&lt;p class=&quot;alert&quot;&gt;&lt;%= alert %&gt;&lt;/p&gt;</pre><h4>Sending the email</h4><p>Very easy, first we are going to generate our mailer, $ rails g mailer EmailLinkMailer and then we give it functionality:</p><pre>class EmailLinkMailer &lt; ApplicationMailer<br>  def sign_in_mail(email_link)<br>    @token = email_link.token<br>    @user = email_link.user</pre><pre>    mail to: @user.email, subject: &quot;Here is your magic link! 🚀&quot;<br>  end<br>end</pre><p>Let’s edit our email (app/views/email_link_mailer/sign_in_mail.html.erb) a little:</p><pre>&lt;p&gt;Hello, &lt;%= @user.email %&gt;!&lt;/p&gt;<br>&lt;p&gt;Recently someone requested a link to enter your account, if it was you, just press the button below to log in&lt;/p&gt;</pre><pre>&lt;%= link_to &quot;Sign in to my account&quot;, email_link_url(/service/token: @token) %&gt;</pre><p>Brilliant! At this point our program is already capable of sending the email, we just need the main view, where the user will give us their email and we can fire all this backend.</p><p>Just add this simple form in app/views/email_links/new.html.erb:</p><pre>&lt;%= form_with(url: magic_link_path, method: :post) do %&gt;<br>  &lt;%= label_tag :email, &quot;E-mail address&quot; %&gt;<br>  &lt;%= email_field_tag :email, nil, placeholder:&quot;carpintinimatias@gmail.com&quot;, autofocus: true, required: true %&gt;<br>  &lt;%= submit_tag &quot;Send!&quot; %&gt;<br>&lt;% end %&gt;</pre><p>To validate on the front that this works, we can add this dummy example in app/views/welcome/index.html.erb:</p><pre>&lt;% if user_signed_in? %&gt;<br>  &lt;p&gt;Hello, &lt;%= current_user.email %&gt;&lt;/p&gt;<br>  &lt;%= link_to &quot;Sign out&quot;, destroy_user_session_path, method: :delete %&gt;<br>&lt;% else %&gt;<br>  &lt;p&gt;Hey, Sign In with Magic Links!&lt;/p&gt;<br>  &lt;%= link_to &quot;Click here&quot;, new_magic_link_path %&gt;<br>&lt;% end %&gt;</pre><p>All right, that’s it. Thanks for reading. 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=582b73ac58ed" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to build a content recommendation engine with Ruby on Rails]]></title>
            <link>https://carpintinimatias.medium.com/how-to-build-a-content-recommendation-engine-with-ruby-on-rails-a6ad16e7b7ab?source=rss-4612a30281d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/a6ad16e7b7ab</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[algorithms]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Matias Carpintini.]]></dc:creator>
            <pubDate>Mon, 28 Sep 2020 01:59:29 GMT</pubDate>
            <atom:updated>2020-09-28T01:59:29.321Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*5uYnxyHokvqnKde7UgSAfQ.jpeg" /><figcaption>Photo by <a href="https://unsplash.com/@freestocks?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">freestocks</a> on <a href="https://unsplash.com/s/photos/netflix?utm_source=unsplash&amp;utm_medium=referral&amp;utm_content=creditCopyText">Unsplash</a></figcaption></figure><p>Just to give you some context, we were working on the new Diabecarp App a few days ago. I can’t talk much about the new features, but I am going to extrapolate 2 interesting solutions during the process, give you why, explain a bit and, as always, put together a demo with Rails ♥️.</p><p><strong>First Requirement -</strong></p><h3>Recommendation engine</h3><p>Without giving many details about the case itself, we have a very large amount of content. Various resources (such as Articles or Recipes). Therefore, we must find a way to organize it efficiently according to the user’s interest. Come on, nothing new, right?</p><p>So, the first thing we did was ask ourselves, what do we have at our disposal to better understand the user and their interests? At this point, due to early stage, we can only use: likes and views.</p><p>The next thing we did was go over the different ways of understanding our user. And we opted for the one that seems simpler, and not for that less elegant.</p><h3>🌎 Collaborative Filtering</h3><p>It is based on the premise that we all have certain similarities, and therefore, likes and interests. And precisely this simplicity is what makes this algorithm extremely elegant.</p><blockquote><a href="https://en.wikipedia.org/wiki/Collaborative_filtering"><strong><em>Wikipedia</em></strong></a><strong><em>:</em></strong><em> Collaborative filtering is a method of making automatic predictions (filtering) about the interests of a user by collecting preferences or taste information from many users (collaborating).</em></blockquote><p>Most websites like Amazon, YouTube, and Netflix use collaborative filtering as a part of their sophisticated recommendation systems. You can use this technique to build recommenders that give suggestions to a user on the basis of the likes and dislikes of similar users.</p><p>Let’s see with an illustration, surely they understand me instantly.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*A_91T5KYJ_iiqZWN.jpg" /></figure><p>It is also very common to see this with <strong><em>Content Based Filtering</em></strong>, the same as with users, only here we compare the relationship of the content. Something like that:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/880/0*YvW6E-pES3U0aZEh.jpg" /></figure><p><strong>DISCLAIMER:</strong> For the rest of the article I will touch on both options, I just want to make it clear that the concept is the same, the similarity.</p><p><strong>👉 Let’s see an example</strong> of how to recommend similar content (in this case, songs).</p><p>First, we take each pair of songs in our database and calculate a similarity between the two songs. To find this similarity, we compared the lists of users who liked the two songs. If many people liked both songs, it is likely that they are quite similar. And if not many people liked both songs, they are probably less similar. A table of similarities could look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/82800e4507e5f0e7c08bf6d755bf9be9/href">https://medium.com/media/82800e4507e5f0e7c08bf6d755bf9be9/href</a></iframe><p>Once we have this list of similarity scores between songs, it’s pretty easy to provide recommendations. If a user is listening to a song, we can provide a “Similar Songs” list by simply finding the most similar songs in our previous metric.</p><h3>Challenges with Collaborative Filtering</h3><p>Basically, there are 2 big problems.</p><p>1.- <strong>Cold Start:</strong><br>Starting without enough data, such as users and reactions of those users that allow us to multiply matrices and reach a good result (later).</p><p>This clear problem has a solution, only that we find a much simpler return. Basically, in the index of each resource (eg. Articles) we have a top section with 10 recommended articles and below the rest ordered by ‘most recent’.</p><p>This is how we get those recent ones to get the traction they deserve. Here it can be automatically filtered to the top section or disappear completely. Finally, we filter those that the user already read and end.</p><p>2.- <strong>Scalability:</strong><br>The more users and more data, the more expensive it becomes to compare these matrices.</p><p>As we do not have much time or resources, we decided to take this technical debt, considering that very possibly in the future we will have to migrate.</p><p>Now let’s see a real implementation so that you can understand me.</p><p>There are already several gems developed for this need, yet several are old. I’m not 100% sure they still work, at the end of the day at Diabecarp we have another stack. Maybe we can write a new one in the future 😉</p><ul><li><a href="https://github.com/Pathgather/predictor">Predictor</a></li><li><a href="https://github.com/davidcelis/recommendable">Recommendable</a></li><li><a href="https://github.com/geoffreylitt/simple_recommender">Simple Recommender</a></li></ul><p>I choose the last one because the rest works with Redis and I no longer want to extend the post. Let’s go! 👊</p><p>To find the similarity of two songs, we need to take the user IDs that liked each of the two songs, and compute: (size of intersection of sets) / (<a href="https://en.wikipedia.org/wiki/Jaccard_index">Jaccard similarity coefficient</a>). Because we have to do this computation for every pair of songs, performance becomes important.</p><p>One strategy used by the Redis-based gems is to push the similarity computation into our datastore– we want to avoid the overhead of sending each pair of ID sets back and forth to our application server, especially if those are large sets. We also get extra performance points if our datastore has primitives that help make the similarity computation faster.</p><p>Fortunately, these are both problems that can be solved with a relational database. SQL is totally flexible enough to express a single query that computes many item similarities at once. Also, postgres happens to have a convenient extension called intarray which provides efficient intersection and union operations for arrays of integers.</p><p><em>Setup the gem…</em><br>Specify an ActiveRecord association to use for recommendation (./app/models/song.rb):</p><pre>class Song &lt; ActiveRecord::Base<br>  has_many :likes<br>  has_many :users, through: :likes</pre><pre>  include SimpleRecommender::Recommendable<br>  similar_by :users<br>end</pre><p>And then you can call similar_items to find similar items based on who liked them:</p><pre>song = Song.find_by(title: &quot;Another Brick in the Wall&quot;)<br>song.similar_items(n_results: 3)<br># =&gt; [#&lt;Song id: 2, name: &quot;Time&quot;&gt;,<br>      #&lt;Song id: 3, name: &quot;Hey You&quot;&gt;,<br>      #&lt;Song id: 4, name: &quot;Wish You Where Here&quot;&gt;]</pre><p>This scope is composing a query that operates on its <em>join table</em>, like a Like table with user_id and song_id. It uses <a href="https://www.postgresql.org/docs/9.2/static/queries-with.html">common table expressions</a> to create a temporary table with one row per pair of songs, and computes the similarity for each row of that table. That temporary table looks something like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3c7b81e3a88bcbb1153b75089c3004cf/href">https://medium.com/media/3c7b81e3a88bcbb1153b75089c3004cf/href</a></iframe><p>Then it just looks for the highest singularity and returns it.</p><p>Ok, that’s it for today. In the following article I would like to talk about how we are using Bayesian Networks or even how we prepare for onboarding.</p><p>BTW, if you are interested in the project, we are still looking for devs!</p><p>👋 Bye</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=a6ad16e7b7ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Real Time Notification System with Sidekiq, Redis and Devise in Rails 6]]></title>
            <link>https://carpintinimatias.medium.com/real-time-notification-system-with-sidekiq-redis-and-devise-in-rails-6-8b69ac4c9f07?source=rss-4612a30281d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/8b69ac4c9f07</guid>
            <category><![CDATA[redis]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Matias Carpintini.]]></dc:creator>
            <pubDate>Mon, 28 Sep 2020 01:42:55 GMT</pubDate>
            <atom:updated>2020-09-28T01:42:55.861Z</atom:updated>
            <content:encoded><![CDATA[<p>In this post, we are going to talk a lot about asynchronous functions, something very fashionable nowadays, but not so much just a few years ago.</p><p>With this I do not mean that it is something necessarily new, but I believe that thanks to the JS ecosystem today the world happens in real time.</p><p>In this post, I want to teach the key concepts of this. But as always, we do not stay in theory and we are going to see a real implementation, such as real-time notifications from our application.</p><p><strong>I will try to be as brief and simple as possible.</strong></p><h4>Definitions and concepts -</h4><p><em>Asynchronous programming:</em> refers to the occurrence of events that happen in our program. They are executed independently of our main program, and never interfere with their execution. Prior to this, we were forced to wait for a response to continue execution, seriously impairing the user experience.</p><blockquote><a href="https://medium.com/swift-india/concurrency-parallelism-threads-processes-async-and-sync-related-39fd951bc61d"><em>Concurrency, Parallelism, Threads, Processes, Async and Sync — Related? 🤔</em></a></blockquote><p><em>WebSockets:</em> WebSockets represent a long awaited evolution in client/server web technology. They allow a long-held single TCP socket connection to be established between the client and server which allows for bi-directional, full duplex, messages to be instantly distributed with little overhead resulting in a very low latency connection. <a href="https://pusher.com/websockets">Keep reading</a></p><p>In other words, it allows us to establish a peer-to-per connection between the client and the server. Before this, the client was only the one who knew where the server was, but not vice versa.</p><p>Thanks to this, we can send a request to the server, and continue executing our program, without waiting for your response. Then the server knows where the client is, and can send you the response.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/0*-taxE2x6zjeYBE64.png" /></figure><h3>Let’s do it 👊</h3><p>All of the above already makes sense for our notification system, right?<br>Before continuing, make sure you have Redis installed. Sidekiq uses Redis to store all of its job and operational data.</p><p>👋 <em>If you do not know what Redis is, you can discover it on its </em><a href="https://redis.io/"><em>official site</em></a></p><p><a href="https://github.com/mperham/sidekiq">Sidekiq</a> helps us to work in the background in a super simple and efficient way. (Also, one of my favorite gems ♥️)</p><p>I created this project for this article in order to focus directly on what interests us. The project is a simple blog with user authentication and the necessary front to display our notifications. You can download it and follow the article with me.</p><p><strong>NOTE:</strong> you can see the full implementation in the “notifications” branch</p><h4>Init configuration…</h4><p>In config/routes.rb we will mount the routes of <a href="https://edgeguides.rubyonrails.org/action_cable_overview.html">ActionCable</a> (framework for real-time communication over websockets)</p><pre>Rails.application.routes.draw do<br>  # everything else...<br>  mount ActionCable.server =&gt; &#39;/cable&#39;<br>end</pre><p>Now, do you remember how WebSockets works? A peer-to-peer connection, well in other words, is also a <em>channel</em> (as we call it in Rails), and within that channel, we have to always identify each user. This so that the server can know who to reply to, and know who made a request. In this case, we will identify it with the user.id (I am using devise)</p><p>So, in app/channels/application_cable/connection.rb:</p><pre>module ApplicationCable<br>  class Connection &lt; ActionCable::Connection::Base<br>    identified_by :current_user</pre><pre>    def connect<br>      self.current_user = find_user<br>    end</pre><pre>    def find_user<br>      user_id = cookies.signed[&quot;user.id&quot;]<br>      current_user = User.find_by(id: user_id)</pre><pre>      if current_user<br>        current_user<br>      else<br>        reject_unauthorized_connection<br>      end<br>    end<br>  end<br>end</pre><p>We are going to save the user who logged in a cookie (it will help us to obtain it from other places, we will see), an interesting solution for this (at least with Devise) is using <a href="https://github.com/warden-stack/Warden/wiki/Hooks">Warden Hooks</a></p><p>For that, we can create an initializer on our application, config/initializers/warden_hooks.rb</p><pre>Warden::Manager.after_set_user do |user, auth, opts|<br>    auth.cookies.signed[&quot;user.id&quot;] = user.id<br>    auth.cookies.signed[&quot;user.expires_at&quot;] = 30.minutes.from_now<br>  end</pre><pre>  Warden::Manager.before_logout do |user, auth, opts|<br>    auth.cookies.signed[&quot;user.id&quot;] = nil<br>    auth.cookies.signed[&quot;user.expires_at&quot;] = nil<br>  end</pre><p>Now, let’s create a table in our database to save every notification we create, for this, $ rails g model Notification user:references item:references viewed:boolean</p><p><strong>NOTE:</strong> <em>:item</em> is a <a href="https://guides.rubyonrails.org/association_basics.html#polymorphic-associations">polymorphic association</a>, I do it this way so they can add various types of notifications)</p><p>Let’s specify this and other details in our migration (db/migrate/TIMESTAMP_create_notifications.rb):</p><pre>class CreateNotifications &lt; ActiveRecord::Migration[6.0]<br>  def change<br>    create_table :notifications do |t|<br>      t.references :user, foreign_key: true<br>      t.references :item, polymorphic: true<br>      t.boolean :viewed, default: false</pre><pre>      t.timestamps<br>    end<br>  end<br>end</pre><p>and, $ rails db:migrate</p><p>In app/models/notification.rb we are going to do a couple of things that we will see on the go</p><pre>class Notification &lt; ApplicationRecord<br>  belongs_to :user<br>  belongs_to :item, polymorphic: true # Indicates a polymorphic reference</pre><pre>  after_create { NotificationBroadcastJob.perform_later(self) } # We make this later</pre><pre>  scope :leatest, -&gt;{order(&quot;created_at DESC&quot;)}<br>  scope :unviewed, -&gt;{where(viewed: false)} # This is like a shortcut</pre><pre>  # This returns the number of unviewed notifications<br>  def self.for_user(user_id)<br>    Notification.where(user_id: user_id).unviewed.count<br>  end<br>end</pre><p>Let’s create a <a href="https://api.rubyonrails.org/classes/ActiveSupport/Concern.html"><em>concern</em></a>, remember that one of the most respected Rails philosophies is DRY (Don’t Repeat Yourself), currently, each notification requires the same to work (in models)(again, in this project we only have publications, but We could have many other things that we want to integrate with our notification system, so with this form it is super simple).</p><p>For that, app/models/concerns/notificable.rb</p><pre>module Notificable<br>  extend ActiveSupport::Concern # module &#39;::&#39;</pre><pre>  included do # this appends in each place where we call this module<br>    has_many :notifications, as: :item<br>    after_commit :send_notifications_to_users<br>  end</pre><pre>  def send_notifications_to_users<br>    if self.respond_to? :user_ids # returns true if the model you are working with has a user_ids method<br>      NotificationSenderJob.perform_later(self)<br>    end<br>  end<br>end</pre><p>Now we can include it in our app/models/post.rb. Remember that our send_notifications_to_users expects the method user_ids to reply to you with the respective fix. Let&#39;s do that (app/models/post.rb):</p><pre>class Post &lt; ApplicationRecord<br>  include Notificable<br>  belongs_to :user</pre><pre>  def user_ids<br>    User.all.ids # send the notification to that users<br>  end<br>end</pre><p>We are going to create the <a href="https://edgeguides.rubyonrails.org/active_job_basics.html">job</a> in charge of sending the notifications, this is what we will send to the background and we will handle with Sidekiq. For that, $ rails g job NotificationSender</p><p>Inside the job (app/jobs/notification_sender_job.rb):</p><pre>class NotificationSenderJob &lt; ApplicationJob<br>  queue_as :default</pre><pre>  def perform(item) # this method dispatch when job is called<br>    item.user_ids.each do |user_id|<br>      Notification.create(item: item, user_id: user_id)<br>    end<br>  end<br>end</pre><p>Finnally, we need to install Sidekiq (and Sinatra for make few things a little more easier), so, in out Gemfile:</p><pre># everything else...<br>gem &#39;sinatra&#39;, &#39;~&gt; 2.0&#39;, &#39;&gt;= 2.0.8.1&#39;<br>gem &#39;sidekiq&#39;, &#39;~&gt; 6.0&#39;, &#39;&gt;= 6.0.7&#39;</pre><p>Don’t forget, $ bundle install</p><p>We are going to tell Rails that we will use Sidekiq for jobs on the queue adapter (config/application.rb):</p><pre># everything else...<br>module Blog<br>  class Application &lt; Rails::Application<br>    # everything else...<br>    config.active_job.queue_adapter = :sidekiq<br>  end<br>end</pre><p>We are also going to set up the routes that Sidekiq provides us, among them, a kind of backoffice for our background (later you can have acces from localhost:3000/sidekiq), very interesting. In config/routes.rb:</p><pre>require &#39;sidekiq/web&#39;<br>Rails.application.routes.draw do<br>  # everything else...<br>  mount Sidekiq::Web =&gt; &#39;/sidekiq&#39;<br>end</pre><p>Now we are going to create the channel through which we will transmit our notifications. $ rails g channel Notification</p><p>In the backend of this channel (app/channels/notification_channel.rb), we will subscribe users:</p><pre>class NotificationChannel &lt; ApplicationCable::Channel<br>  def subscribed<br>    stream_from &quot;notifications.#{current_user.id}&quot; # in this way we identify to the user inside the channel later<br>  end</pre><pre>  def unsubscribed<br>    # Any cleanup needed when channel is unsubscribed<br>  end<br>end</pre><p>And in the frontend of the channel (app/javascript/channels/notification_channel.js) it would be interesting to send a push notification to the browser, there are many JS libraries that make that very easy (like <a href="https://pushjs.org/">this</a>), but in order not to make the post much heavier, we are going to print a simple message on the console. So:</p><pre>// everything else...<br>consumer.subscriptions.create(&quot;NotificationChannel&quot;, {<br>  // everything else...<br>  received(data) {<br>    if(data.action == &quot;new_notification&quot;){<br>      cosole.log(`New notification! Now you have ${data.message} unread notifications`) <br>    } // we will define action &amp; message in the next step<br>  }<br>});</pre><p>At this point, we already have a lot running, let’s send that notification to the user! For this we are going to create another job that just does this, remember, the previous job is in charge of creating the notifications, this one does the broadcast. So, $ rails g job NotificationBroadcast</p><p>Inside app/jobs/notification_broadcast_job.rb:</p><pre>class NotificationBroadcastJob &lt; ApplicationJob<br>  queue_as :default</pre><pre>  def perform(notification)<br>    notification_count = Notification.for_user(notification.user_id)</pre><pre>    ActionCable.server.broadcast &quot;notifications.#{ notification.user_id }&quot;, { action: &quot;new_notification&quot;, message: notification_count }<br>  end<br>end</pre><p>Fantastic, we already have everything working! 🎉<br>I’m going to add a few things to the backend to end the example.</p><p>First of all, I’m going to add a method to my user model so I can count the notifications I haven’t seen yet. And the model is a good place to do this query. In app/models/user.rb:</p><pre>class User &lt; ApplicationRecord<br>  # everything else...<br>  def unviewed_notifications_count<br>    Notification.for_user(self.id)<br>  end<br>end</pre><p>I’m also going to create a controller, $ rails g controller Notifications index. Inside the controller (app/controllers/notifications_controller.rb) i&#39;m going to add some methods:</p><pre>class NotificationsController &lt; ApplicationController<br>  def index<br>    @notifications = Notification.where(user: current_user).unviewed.leatest</pre><pre>    respond_to do |format|<br>      format.html<br>      format.js<br>    end<br>  end</pre><pre>  def update<br>    @notification = Notification.find(params[:id])</pre><pre>    message = @notification.update(notification_params) ? &quot;Viewed notification&quot; : &quot;There was an error&quot;</pre><pre>    redirect_to :back, notice: message<br>  end</pre><pre>  private<br>  def notification_params<br>    params.require(:notification).permit(:viewed)<br>  end<br>end</pre><p>I will create a js view to be able to respond remote and display the latest notifications in my dropdown in the nav. In app/helpers/notifications_helper.rb:</p><pre>module NotificationsHelper<br>  def render_notifications(notifications)<br>    notifications.map do |notification|<br>      render partial: &quot;notifications/#{notification.item_type.downcase}&quot;, locals:{notification: notification}<br>    end.join(&quot;&quot;).html_safe<br>  end<br>end</pre><p>Add the link in your nav, in my case (app/views/partials/notifications.html.erb):</p><pre>&lt;%= link_to notifications_path, remote: true, data:{ type:&quot;script&quot; } %&gt;</pre><p>Let’s not forget to add the paths (app/config/routes.rb) for this new controller.</p><pre># everything else...<br>Rails.application.routes.draw do<br>  # everything else...<br>  resources :notifications, only: [:index, :update]<br>end</pre><p>Just create a partial for this item (like app/views/notifications/_post.rb). They can include a link to &#39;mark as seen&#39;, in this way:</p><pre>&lt;%= link_to notification_path(id: notification, notification:{viewed: true}), method: :put %&gt;</pre><p>To run this locally you will have to run Redis ($ redis-server) and Sidekiq ($ bundle exec sidekiq) + $ rails s, have 3 terminal windows open with these 3 commands running in parallel.</p><p>That is all, I hope it is useful to you 👋</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8b69ac4c9f07" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Historia de Diabecarp]]></title>
            <link>https://carpintinimatias.medium.com/historia-de-diabecarp-bb7e782a10db?source=rss-4612a30281d1------2</link>
            <guid isPermaLink="false">https://medium.com/p/bb7e782a10db</guid>
            <category><![CDATA[diabetes]]></category>
            <category><![CDATA[founders]]></category>
            <category><![CDATA[entrepreneur]]></category>
            <category><![CDATA[diabecarp]]></category>
            <dc:creator><![CDATA[Matias Carpintini.]]></dc:creator>
            <pubDate>Thu, 23 Jan 2020 00:54:47 GMT</pubDate>
            <atom:updated>2020-03-20T01:50:23.575Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fI-em9YpwfaNJ3GHP0RUTg.jpeg" /><figcaption>Matias Carpintini, Founder &amp; CEO at <a href="https://diabecarp.com/">Diabecarp</a>.</figcaption></figure><p>Este proyecto nació un 12 de Febrero del 2018. Yo tenía unos 15 años, hace un tiempo había comenzado a programar. Hasta darme cuenta que trabajar para el sueño de alguien más no era lo que más me motivaba. Quería trabajar en mis propios sueños, eso lo tenía claro. Lo que no tenía tan claro era en qué específicamente, tenía que tener una misión que me mueva y ser súper escalable…</p><p>Desde más chico organizaba <a href="https://es.wikipedia.org/wiki/Hackathon">hackathons</a> online (maratón de programadores), hasta que llegó la hora de uno más. El chiste era resolver problemas, crear algo nuevo, diferente. Mi viejo tiene <a href="https://es.wikipedia.org/wiki/Diabetes_mellitus_tipo_1">Diabetes Tipo 1</a>, y mi hermano también, por lo que la enfermedad era algo super normalizado para mi.</p><p>Buscando una idea para llevar a cabo en el evento, noté que ellos aún llevaban todo el registro de sus glucemias, actividad física y demás datos relevantes en una libreta. El control era obligatorio, esto se compartía con el médico en la consulta, y sobre eso se tomaban decisiones importantes. El proceso era muy ineficiente y tedioso. Uno puede olvidar registrar, mentir o lo que sea.</p><p>Como se pueden imaginar, la idea inicial fue desarrollar una app que haga de este proceso algo más llevadero, fin. No había mucho tiempo, solo 3 días de puro código y, terminamos siendo 2 en un team inicial de 6… Lo que pasó después fue tan normal como en otros eventos del estilo, no llegabamos a terminarlo, el otro dev no estaba interesado en llevarlo adelante y, finalmente desarrollamos otra idea.</p><p>Definitivamente con algo me había quedado…</p><p>Meses después, estaba terminando varios proyectos como freelancer, y antes de salir a tomar otros, regresó la idea de ese hackathon. Me lanzo a crear un MVP (Producto Mínimo Viable). 2 semanas después tenía una web-app lista. Valido la idea con comunidades en las que ya me encontraba. El feedback fue duro, la app no era usable, obvio existen otras opciones y yo estaba super early como para dar un diferenciador y/o visión transparente. Pero había descubierto algo, podía automatizar la recomendación de dosis de insulina en una simple calculadora de bolo. Esto ya tenía un mejor olor.</p><p>Tomo las variables básicas, mejoro UI/UX, conecto todo a una base de datos de alimentos (para un buscador dentro de la app) y lanzo otra vez. El usuario solo debía buscar lo que iba a comer, su nivel de glucemia actual y, la app se encargaba del resto. Al mismo tiempo, creo un blog y otro módulo de recetas.</p><p>No mucho después, el boom inicial de un lanzamiento (gracias a influencers, FB Ads, etc) había dejado números difíciles de sostener… Malabareando con el desarrollo, contenido y demás, llego a un punto donde se me hace difícil seguir adelante. Estaba en un bache.</p><p>En ese momento, me urgía delegar la parte de content. No era lo que más me gustaba y, me quitaba 60% del tiempo. Después de analizar varias opciones, decidí hablar con Joaquín Castañeira (ex CMO de Diabecarp). Vivíamos a solo cuadras de distancia, fuimos juntos al colegio y, resulta que los objetivos a largo plazo parecían ligeramente alineados. Nos reunimos en un café y, después de charlar por un rato le acerco la oferta. No lo dudó. Al día siguiente ya no me encargaba del contenido. Por lo que ahora, estaba más enfocado en lo que me interesaba. El algoritmo, la herramienta.</p><p>No pasó mucho tiempo hasta que tuvimos que frenar por completo todo el proyecto. Emprender duele. En ese momento sentía que había perdido un hijo. Las razones fueron muchas, cuestiones personales, técnicas, y otras cosas externas que nos limitaban a ambos.</p><h4>Keep looking forward…</h4><p>Invierno 2019, tocaba organizar otro hackathon (2 ediciones al año). El evento era cada vez más grande (a nivel de participantes al menos), y por lo tanto se hacía complejo llevar todo entre 3 personas (normalmente lo organizaba con otros 2 amigos). Decidí invitar a Joaco y Diego, lo encaramos juntos. Hacía rato que no hablábamos, y lo de Diabecarp surgió. Cuando lo más difícil, eso que nos había frenado, parecía haber pasado. Termina el evento.</p><p>Días después, en medio de clases me llega un email de <a href="https://500.co/">500 Startups</a>, el batch 11 estaba a la vuelta de la esquina. Yo había aplicado en Batch 10. Era lo último que faltaba. Salgo de clases decidido, al salón de al lado, donde estaba Joaco. Le digo que Diabecarp estaba de vuelta. No importaba nada.</p><p>El mismo día contraté a un diseñador para la nueva imagen de marca. <strong>No éramos los mismos, y tenía que saberse.</strong></p><p>Ek 10 de Agosto comenzamos a trabajar. Teníamos como objetivo lanzar todo eso que más nos había funcionado, en <strong>1 mes</strong>. Días antes de la fecha, pensamos que era buena idea contactar a los medios. Una entrevista lleva a la otra, y en unas 2 semanas habíamos salido en cual radio había a unos 300–600 km a la redonda. Diarios, eventos y hasta un canal de TV. 20 de Septiembre fue el lanzamiento. El ruido que se generó fue muy loco.</p><p>Hoy, 4 meses después, sucedieron tantas cosas que no alcanzaría a resumirlo en menos de lo que te duermes leyendo este artículo.</p><p>Para terminar, <strong>quiero que se queden con lo siguiente</strong>:</p><p>Si tu sueño no te quita el sueño, quizá ese sueño no sea lo suficientemente grande. Trabaja en lo que amas, solo tienes una vida.</p><p>Será difícil, lo sé, pero, nada que valga verdaderamente la pena es fácil de conseguir. Y esa es, quizá, la mejor parte. Eso es lo que lo hace tan especial, tan exclusivo.</p><p>Ten el cuenta que el tiempo pasará de todas formas… El que se arriesgó, y el que no, terminan en el mismo lugar.</p><p>Créetela, y sigue adelante. Criticarán de todas formas. Te dirán loco, dirán que pierdes el tiempo, o que busques un trabajo de verdad. Dirán que no naciste en la familia correcta, el lugar adecuado, que no es momento, dirán que no eres lo suficientemente inteligente pero, <strong>la única realidad es la que tu crees</strong>.</p><p>Play your own game, put in the fucking work and, enjoy the journey.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bb7e782a10db" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>