<?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 Emir Vatric on Medium]]></title>
        <description><![CDATA[Stories by Emir Vatric on Medium]]></description>
        <link>https://medium.com/@vatricemir?source=rss-146b58c03e1a------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*tNTRLx-y1vyirv_HN572RA.jpeg</url>
            <title>Stories by Emir Vatric on Medium</title>
            <link>https://medium.com/@vatricemir?source=rss-146b58c03e1a------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 18:43:55 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vatricemir/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[Simple Trick for Lightning-Fast LIKE and ILIKE Queries]]></title>
            <link>https://levelup.gitconnected.com/simple-trick-for-lightning-fast-like-and-ilike-queries-bdbf9eeba309?source=rss-146b58c03e1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/bdbf9eeba309</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[query-optimization]]></category>
            <category><![CDATA[postgresql]]></category>
            <dc:creator><![CDATA[Emir Vatric]]></dc:creator>
            <pubDate>Sat, 07 Jan 2023 21:01:36 GMT</pubDate>
            <atom:updated>2023-01-10T18:32:51.215Z</atom:updated>
            <content:encoded><![CDATA[<p>Improve Search Performance with Trigram Indexes in PostgreSQL</p><h4>TLDR;</h4><ol><li>Enable <strong>pg_trgm</strong> extension</li><li>Add Trigram Index on columns that you are doing a full-text search</li></ol><pre>class AddTrigramIndex &lt; ActiveRecord::Migration[6.0]<br> disable_ddl_transaction!<br><br> def change<br>   enable_extension :pg_trgm<br><br>   add_index :table, :column, opclass: :gin_trgm_ops, using: :gin, <br>             algorithm: :concurrently, name: ‘index_trgm’<br> end<br>end</pre><p><strong>And that is it!</strong> Now you can leave and be happy that you have made a massive improvement or you can read on and actually understand what happened!</p><h3>Introduction</h3><p>What is the best part of software development? <strong>Optimizing! </strong>Optimizing code, optimizing queries, optimizing data models, fixing google speed score whenever something like this lands in your lap you should be over the moon! You will never do so little (usually) and achieve such a big change for the end user!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/496/1*lA4e3nPixeZxA_ZlUHgLBg.gif" /><figcaption>One obligatory cheesy meme</figcaption></figure><p>Now here is what happened, some time ago you added a search feature to your dashboard, the app was small so you didn’t care about performance.</p><pre>def search(query)<br>  Post.where(&quot;body ILIKE (?)&quot;, &quot;%#{query}%&quot;)<br>end</pre><p>At the time of writing, this was fine there were not too many posts and a sequential scan was quick enough, but fast forward to today this query is too slow and we need to fix it.</p><h3>What is a Trigram Index?</h3><blockquote>A trigram index is a type of inverted index. Trigram indexes are used to efficiently search for strings in large tables without providing an exact search term.</blockquote><p>Trigram indexes make <a href="https://www.postgresql.org/docs/current/pgtrgm.html">substring and similarity match</a> efficient by indexing the unique trigrams of a string.</p><p>From the definition we are left with two questions:</p><ol><li>What is a trigram?</li><li>What is an inverted index?</li></ol><p>A <strong>trigram</strong> is a group of three consecutive characters in a string.</p><pre>SELECT show_trgm(&#39;trigram&#39;);</pre><pre>               show_trgm<br>    -------------------------------<br>{&quot;  t&quot;,&quot; tr&quot;,&quot;am &quot;,gra,igr,ram,rig,tri}</pre><p>Generalized <strong>Inverted Index</strong> or GIN for short is an index type designed to deal with data types that are subdividable. An index is going to store a key and a reference where that value occurs.</p><p>Another way of explaining GIN indexes is that it is like the table of contents in a book, where the heap pointers (to the actual table) are the page numbers. Multiple entries can be combined to yield a specific result, like the search for “compensation accelerometers” in this example:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*C9Qzmf-taMPJj3xcEfjl3g.png" /><figcaption><a href="https://wiki.postgresql.org/images/2/25/Full-text_search_in_PostgreSQL_in_milliseconds-extended-version.pdf">presentation by Oleg Bartunov and Alexander Korotkov</a></figcaption></figure><p>To summarise let’s say that we have an indexed body column in our posts table, and the body of the post is a STRING Trigram Index</p><pre>SELECT show_trgm(&#39;Trigram Index&#39;);<br><br>-----------------------<br><br>{&quot;  i&quot;,&quot;  t&quot;,&quot; in&quot;,&quot; tr&quot;,&quot;am &quot;,dex,&quot;ex &quot;,gra,igr,ind,nde,ram,rig,tri}</pre><p>All of the substrings Trigram Index are going to be pointing to the post record. Once we make a query trying to match a keyword gram database is going to split a keyword into trigrams and do Bitmap Index Scan matching them to the trigrams in the index.</p><pre>SELECT show_trgm(&#39;gram&#39;);<br><br>-----------------------<br><br>{&quot;  g&quot;,&quot; gr&quot;, &quot;am &quot;, gra, ram}<br>-------------match--match-match</pre><p><strong>I am sure that there is much more happening than this but as I understand this is the gist of it!</strong></p><p>Trigram indexes are much more powerful depending of the comparison used:</p><p>Trigram indexes on STRING columns support the following comparison operators:</p><ul><li><strong>equality</strong>: =. Note that standard btree secondary indexes may perform better than trigram indexes for equality searches.</li><li><strong>pattern matching (case-sensitive)</strong>: LIKE</li><li><strong>pattern matching (case-insensitive)</strong>: ILIKE</li><li><strong>similarity matching</strong>: %. This operator returns true if the strings in the comparison have a similarity that meets or exceeds the threshold.</li></ul><p>There are a few cons to all of this and one of them is <strong>slower writes on large tables</strong>!</p><h3>Trigram index in action</h3><p>I didn’t want to leave the subject without a quick example, I quickly created 40k users in the database and run a simple ILIKE query on the users&#39; email.</p><pre>SELECT &quot;users&quot;.* FROM &quot;users&quot; WHERE users.email ILIKE (&#39;%emir%&#39;);</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/930/1*pWc67Qw48BqschWN6Am1Ig.png" /></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/938/1*1Giou1-SLiKYuha8_qlHbA.png" /><figcaption>Left: query plan without index, database doing a sequential scan, total time: ~28.5 ms | Right: query plan uses index, total time: ~1.3 ms</figcaption></figure><p>Even on a dataset this small and as simple as it gets email column difference is more than noticeable. On larger datasets, larger columns ( think article body ) or more complex queries where we try to search in multiple fields results are going to be much more significant!</p><h3>Conclusion</h3><p>Enabling the pg_trgm extension and adding a trigram index can be a simple and effective way to improve the performance of LIKE and ILIKE queries in PostgreSQL. By taking advantage of the specialized data structure and algorithms provided by trigram indexes, you can ensure that your queries run quickly and efficiently, providing a better experience for your users.</p><h3>References</h3><p>Big thank you to the <a href="https://pganalyze.com/">pganalyze</a> team and their awesome <a href="https://pganalyze.com/blog">blog</a>!</p><h3>Level Up Coding</h3><p>Thanks for being a part of our community! Before you go:</p><ul><li>👏 Clap for the story and follow the author 👉</li><li>📰 View more content in the <a href="https://levelup.gitconnected.com/?utm_source=pub&amp;utm_medium=post">Level Up Coding publication</a></li><li>🔔 Follow us: <a href="https://twitter.com/gitconnected">Twitter</a> | <a href="https://www.linkedin.com/company/gitconnected">LinkedIn</a> | <a href="https://newsletter.levelup.dev/">Newsletter</a></li></ul><p>🚀👉 <a href="https://jobs.levelup.dev/talent/welcome?referral=true"><strong>Join the Level Up talent collective and find an amazing job</strong></a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=bdbf9eeba309" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/simple-trick-for-lightning-fast-like-and-ilike-queries-bdbf9eeba309">Simple Trick for Lightning-Fast LIKE and ILIKE Queries</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to succeed as a self-taught developer?]]></title>
            <link>https://levelup.gitconnected.com/how-to-succeed-as-a-self-taught-developer-5c33e5ce656c?source=rss-146b58c03e1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/5c33e5ce656c</guid>
            <category><![CDATA[guides-and-tutorials]]></category>
            <category><![CDATA[self-improvement]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[junior-developer]]></category>
            <category><![CDATA[self-taught-developer]]></category>
            <dc:creator><![CDATA[Emir Vatric]]></dc:creator>
            <pubDate>Sun, 18 Jul 2021 17:10:12 GMT</pubDate>
            <atom:updated>2021-07-19T00:51:13.200Z</atom:updated>
            <content:encoded><![CDATA[<p>Feeling stressed, and overwhelmed? That’s normal!</p><blockquote>The <strong>beginning</strong> is perhaps <strong>more difficult</strong> than anything else, but keep heart, it will turn out all right.</blockquote><p>Starting a new project is stressful, let alone a whole new industry, feelings of fear and cluelessness are overwhelming and you start thinking you are a lost cause. These are common symptoms for every beginner developer, especially if you are a self-taught developer trying to switch a career.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/780/1*ZiTiCYOdbIyovzTSP2E0-A.jpeg" /></figure><p>I have had the same thoughts, fears, family that depends on me while I am exploring this new thing. How to get a job? How to progress as a beginner developer? How to be respected in the field? Let’s try to find answers together.</p><h3>Is this career for you?</h3><p>This is the most important question to answer. Ask yourself why are you on this journey, is your motivation right? How does it feel, like hard work or fun?</p><p>Chances are if you are reading this article that you are the right candidate for this job, and that you are not forcing yourself just because it is cool.</p><h3>Pick your poison</h3><p>The software industry is a rapidly evolving one, new tools, hardware, languages get published almost daily each more important than others. I have seen so many developers fall for this trap, switching languages, frameworks, and whole fields way too early.</p><p>Debates about the best current frameworks or programming languages regularly happen in web development, and there is always an easier and faster new framework to learn. But this doesn’t have to mean that the language and framework that you are working in is going away, they are all there to stay!</p><p>Decide what you want to do, frontend or backend and focus hard on it, pick a language, in my opinion, avoid the most popular ones that everyone is doing, you have a much better prospect for a job in languages that are the latest buzz!</p><h3>Work at it hard!</h3><p>Udemy, Youtube, Bootcamps all offer amazing and easy-to-access knowledge about anything that you are interested in, use it but don’t abuse it. Going through one beginner course is more than enough to understand some core principles of a subject, don’t forget you will not always have a guiding hand in solving issues start solving them on your own.</p><p>When you get some initial knowledge start coding your own app, from scratch, this is by far the best way to practice and acquire new skills. When you start working for the first year everything will be a learning experience, get to know what is the fastest way to learn new things, this could make or break your career.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/319/1*bBuY5PjARaMn3FCWzcsdzQ.jpeg" /></figure><p>Read books. They often provide focused well-thought content for you. They increase your vocabulary and comprehension, teach you about the concepts that you would not think about googling yourself, and as an added benefit you just sound smart once you start dropping that knowledge in an interview, quite a few times in an interview I got asked if I read books, while it is not a huge offense not to read them, it is a huge plus in anybody&#39;s mind, this shows your interest in the subject and industry as a whole.</p><p>Do coding challenges to flex that problem-solving muscle, learn about basics and data structures, don’t just focus on the framework, basics are important too.</p><p>One important thing, that was a huge help to me, is coding every day. I loved to pick big apps to build, I had some awesome ideas for products that I would build, the truth is, code was garbage and they have never seen production but all the problems and creative ways I used to solve them helped me a lot!</p><p>Here the biggest hurdle to pass is staying motivated, at this stage you will spend about 6–7 months ( or even more ), building, reading, and repeating. I think it is important not to rush this step, and start applying to the jobs while you are still not ready. In order to keep me motivated, I love to listen to podcasts and they are also a great source of education!</p><h3>Build online presence</h3><p>Once you feel ready or you have spent 6 months or more working on your technical skills, and you have a few more demanding apps to show for it, it is time for you to start looking for that first job.</p><p>The first step is building your <strong>portfolio website</strong>, this is your proving ground, this is the place where you will flex your skills for employers googling you, it is extremely important for your website to leave a great first impression! <em>Internet is full of tutorials and guides on how to put the right content there, read them.</em></p><p><strong>Make a resume</strong>, and this is a scary one, what should you put where it says Experience? Well, those projects that you built count as experience, they are there to show your skills! <em>Internet is full of tutorials and guides on how to put the right content there, read them.</em></p><p>One important part of getting noticed is <strong>writing articles</strong>, while you might feel like you are not experienced enough to do so, don’t worry just write them. Writing technical articles says much about you, they demonstrate your interest and motivation, also research about the subject for the article will help you understand the subject better. So stop doubting yourself and start writing!</p><p>Start <strong>making profiles</strong> on dev websites, dev.to, LinkedIn, Upwork, and others. All of these show up on google and make the information about you accessible. <em>Internet is full of tutorials and guides on how to put the right content there, read them.</em></p><p>Don’t ignore the <strong>soft skills,</strong> look up some of the questions that you might get on the interview, be kind and be on time!</p><h3><strong>Summary</strong></h3><p>While this might feel too much to do and a year seems like too long, don&#39;t forget that this is an investment. It is important to be ready for your first job experience!</p><p>Getting the first good job is difficult and frustrating, don’t get discouraged when you get ghosted or rejected it is all part of the process. Stay on your grind, learn some more, write a little bit more, in the end, it all pays off!</p><p>In your first job look for knowledge rather than salary, time to make a bank will come later on. If you find a company that offers you mentorship and challenging tasks know that you have hit the gold.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5c33e5ce656c" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/how-to-succeed-as-a-self-taught-developer-5c33e5ce656c">How to succeed as a self-taught developer?</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[3 tips to up your RSpec game]]></title>
            <link>https://levelup.gitconnected.com/3-tips-to-up-your-rspec-game-fd4f4b3b39b4?source=rss-146b58c03e1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/fd4f4b3b39b4</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[rspec]]></category>
            <dc:creator><![CDATA[Emir Vatric]]></dc:creator>
            <pubDate>Mon, 15 Feb 2021 01:29:18 GMT</pubDate>
            <atom:updated>2021-03-15T00:58:54.321Z</atom:updated>
            <content:encoded><![CDATA[<h4>Tests, annoying but useful!</h4><p>In day-to-day work every developer should be asked to write tests for their work, and if one is not asked he should ask for them. While they are cumbersome and annoying to write, and usually are an afterthought, they come really useful down the line when refactoring the code, upgrading the framework, or using them as a form of documentation for the feature.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*yABDxybRlXqJoDxm" /><figcaption>Photo by <a href="https://unsplash.com/@karishea?utm_source=medium&amp;utm_medium=referral">Kari Shea</a> on <a href="https://unsplash.com/?utm_source=medium&amp;utm_medium=referral">Unsplash</a></figcaption></figure><p>Here are a few tips that helped me to write cleaner, more structured, and overall better specs. Implementing these tips will also streamline your workflow and give you direction and a better idea on how to go on about testing in general.</p><h3>Structure the code</h3><p>If we embrace the premise that tests are going to serve as documentation for our code, that it is important to write descriptive tests, and use what framework provides us with<strong> describe, context, it</strong>.</p><p>Here is an example from an open-source project called <a href="https://github.com/chatwoot/chatwoot/blob/develop/spec/controllers/api/v1/profiles_controller_spec.rb">ChatWoot</a>, which I can’t recommend enough for you to check.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/49e9afacedb674eeee9641c5ba4e69da/href">https://medium.com/media/49e9afacedb674eeee9641c5ba4e69da/href</a></iframe><p>In this example, it is easy to understand what we are testing, and how it is supposed to behave given the context. So now when somebody else is trying to do the work, instead of reading the code, he can read the specs and understand what is the purpose of given endpoints.</p><h3>Use Data Factories</h3><p>Data Factory (or <em>factory</em> in short) is a blueprint that allows us to create an object, or a collection of objects, with predefined sets of values. While you can do your work without them, you definitely should use them. Factories will make your code DRY and your workflow faster and easier.</p><p>I personally use <a href="https://github.com/thoughtbot/factory_bot_rails">FactoryBot</a>, it is easy to set up and there is almost no learning curve, everything you need is well documented and easy to implement.</p><p>Let’s take a look at a quick example, considering this model:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8c834f687f83546191c55b19a01a707e/href">https://medium.com/media/8c834f687f83546191c55b19a01a707e/href</a></iframe><p>We can produce a factory that can create all the necessary data for one object:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/cad283e8735eb5c41e0c60940a154b05/href">https://medium.com/media/cad283e8735eb5c41e0c60940a154b05/href</a></iframe><p>From reading this gist we can conclude that next time we want to create an article object, that is published with user auto-created we can just call:</p><pre>create :article, :published</pre><p>From this single line, we will create a new Article, and User object with name and status attributes, obviously these can be overridden if we pass different values for them, this is obviously a lot better than creating multiple objects manually.</p><p>But this is not all that FactoryBot has to offer, it has all kinds of useful callbacks built for different scenarios that you might run into. All of these features are made to make your life easier, and your code cleaner, it is definitely worth looking into, <a href="https://github.com/thoughtbot/factory_bot/blob/master/GETTING_STARTED.md">Getting Started</a>.</p><h3>Track your Cove Coverage</h3><p>The best way to know if you have tested your code well is to track your coverage with one of the tools designed to do just that. Note that checking if your code is covered is not as same as checking if your tests are effective.</p><p>Having your codebase covered with tests is very useful, and it is a sign of a healthy project and responsible developers.</p><p>To check my code coverage I use <a href="https://github.com/simplecov-ruby/simplecov">SimpleCov</a>, it is simple to set up and gives you great data to check your coverage line by line.</p><p>Setup is easy, add simplecov to your gemfile, and in top of your <em>spec_helper.rbor </em><em>rails_helper add:</em></p><pre>require &#39;simplecov&#39;<br>SimpleCov.start :rails</pre><p>And setup is done after your specs are done running you will get generate an HTML file that is super easy to understand and read.</p><h3>Conclusion</h3><p>Love them or hate them, testing your code is an integral part of every developer&#39;s day, as soon as you embrace writing test, and start considering them as a big part of the development process, rather them an afterthought life is going to become easier.</p><p>These tools helped me to up my Rspec game, and I had to learn it the hard way, all the way from the beginning when I wasn&#39;t paying the attention to my coverage till now when I have to go back and cover the missed lines.</p><ul><li><a href="https://rspec.info/">RSpec: Behaviour Driven Development for Ruby</a></li><li><a href="https://github.com/simplecov-ruby/simplecov">GitHub - simplecov-ruby/simplecov: Code coverage for Ruby with a powerful configuration library and automatic merging of coverage across test suites</a></li><li><a href="https://github.com/thoughtbot/factory_bot_rails">GitHub - thoughtbot/factory_bot_rails: Factory Bot ♥ Rails</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fd4f4b3b39b4" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/3-tips-to-up-your-rspec-game-fd4f4b3b39b4">3 tips to up your RSpec game</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[A Closer Look at Default_Scope]]></title>
            <link>https://levelup.gitconnected.com/a-closer-look-at-rails-default-scope-eb260744f196?source=rss-146b58c03e1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/eb260744f196</guid>
            <category><![CDATA[rubygems]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[software]]></category>
            <category><![CDATA[software-development]]></category>
            <dc:creator><![CDATA[Emir Vatric]]></dc:creator>
            <pubDate>Tue, 12 Jan 2021 05:33:39 GMT</pubDate>
            <atom:updated>2021-01-12T05:33:39.477Z</atom:updated>
            <content:encoded><![CDATA[<h4>Is it really bad or just misused?</h4><p>Some years ago, I had this amazing idea for a startup, but since it is a tech company it required some coding and actually creating a product, “so what” I thought, let&#39;s learn it, after all, how difficult can it really be. After 3 years of learning and working as a Ruby developer in the industry, I forgot about my project and actually fall in love with the craft itself, but a few months ago I decided that as a side project I should start working on it, so it began.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/640/1*uYwTWTDTX1MH8F38-17_9Q.jpeg" /></figure><p>Few years of experience and a few books later I was ready to get my hands dirty, but first things first, the app that I am building has multitenant architecture, so the app needs to have a nice, easy to use and efficient way of scoping the data by a tenant, “easy” I thought, default_scope is here, but little did I know that community hated it for its shortcomings, so let&#39;s get into it.</p><p>First, let us get familiar with the scopes in general, this will be a quick overview of parts that are relevant to the main topic.</p><h3>What are scopes?</h3><blockquote>Scopes are a great Rails tool to keep stuff DRY and well organized. It’s not complicated though, it’s just a set of pre-defined queries that can easily be chained to build complex queries.</blockquote><blockquote>Scopes are custom queries that you define inside your Rails models with the scope method. They take two arguments, a name, and a lambda which implements the query.</blockquote><p>So by definition, a simple scope would look like this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c77e1dee7015886713598988d5ce5ce6/href">https://medium.com/media/c77e1dee7015886713598988d5ce5ce6/href</a></iframe><p>So, now we have created a scope, which allows us to move this simple query from views and controller to a model, also it keeps our code nice and DRY. Like Ruby class methods, to invoke the named scopes, simply call it on the class object. Named scopes always return an <strong>ActiveRecord::Relation </strong>object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1fc52624d2a4f836d73bef283ed8ca59/href">https://medium.com/media/1fc52624d2a4f836d73bef283ed8ca59/href</a></iframe><p>There is a lot more to the scopes and scopes aren’t doing anything magical or super special. They’re just methods. You could do the same thing using class methods!</p><h3>What is a default_scope?</h3><p>Default scopes, when defined, are automatically applied to the model, and if you try googling them you will find quite a few articles on why <strong>not to use</strong> them with some great points and examples, so let&#39;s go through some of them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*xtfFs2nnqEVbPLJ_ZaCNUw.jpeg" /></figure><p>First, let’s see how it is defined in our trusty example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c62c6edd62de5c585e048c1403044b79/href">https://medium.com/media/c62c6edd62de5c585e048c1403044b79/href</a></iframe><p>At the first glance, this seems wrong, and it is, we are changing the expected behavior, and after a few months, you might be left confused with queries that are coming from Product and it will cost you the time to debug and ultimately refactor this code. But it doesn&#39;t end there, we still have a few more consequences of using default scopes.</p><p>The default_scope is also applied while creating/building a record. It is not applied while updating a record.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/846c8e28eb2c001b87b4d66b25209df3/href">https://medium.com/media/846c8e28eb2c001b87b4d66b25209df3/href</a></iframe><p>As we can see initializing or creating a new record will be affected by the scope unless overridden. The default scope can get really complicated when using associations and trying to get all the associated records unscoped.</p><p>Let&#39;s consider an example:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/1f94d35fdc3f967dbab188a7f54993cf/href">https://medium.com/media/1f94d35fdc3f967dbab188a7f54993cf/href</a></iframe><p>This is an issue, there is a reasonable use-case where you would want to use unscoped data. Here we can find a few solutions for this issue produced from the community, but none of them seemed like an ideal solution for the issue.</p><p>Some examples include, but they usually lead to even more issues down the line and pose even greater issues to the maintainability of the code.</p><blockquote>belongs_to :user, -&gt; { unscope(where: :published) }</blockquote><p>At first look, this seems to be resolving the issue, but is introducing a new one, what if I want to query published products from a user, should I define a new scope, should I not?</p><p>All of these issues could be avoided by using named scopes, and this is a prime example where default_scope should not be used, but is there a case where we can justify issues that we will be introducing to our code?</p><h3>When to use it?</h3><p>In my opinion, <strong>yes</strong>, there are cases when separating the data is extremely important, and using unscoped records would be an exception from the rule. We can look at two examples, first, you are building a multitenant, and second, you primarily in 99% of the cases want to show that specific set of data, like in cases when you would be using <a href="https://github.com/ActsAsParanoid/acts_as_paranoid">act_as_paranoid</a> gem.</p><p>So how do these gems go about implementing default_scope ( since that is what they are using in the background), <a href="https://github.com/ErwinM/acts_as_tenant">acts_as_tenant</a> does a pretty good job of scoping you data per tenant and they outline it their documentation on how to use their default scope:</p><blockquote>Adding acts_as_tenant to your model declaration will scope that model to the current tenant BUT ONLY if a current tenant has been set.</blockquote><p>So how did they approach the issues around the current scope?</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/ee1eceffaf94a850df181bfdc650a818/href">https://medium.com/media/ee1eceffaf94a850df181bfdc650a818/href</a></iframe><p>As we can see here ( unless I am missing something ) they don’t, they understand that scoping data is far more important than 1% cases where you would want to get a different set of data, and the same goes for gems like act_as_paranoid. And for initializing new objects with a tenant already set makes a ton of sense.</p><p>And in the few cases when we need to use the data out of that default scope we can use <a href="https://apidock.com/rails/ActiveRecord/QueryMethods/unscope"><strong>unscope</strong></a> or <a href="https://apidock.com/rails/ActiveRecord/Base/with_exclusive_scope/class"><strong>with_exclusive_scope</strong></a><strong>.</strong></p><h3>Conclusion</h3><p>Using default scope, in general, should be avoided, more often than not it will cause issues down the line, it introduces a lot of unexpected behavior when used incorrectly.</p><p>But in those cases where it makes sense don&#39;t be afraid to use it, just make sure it is well documented.</p><h3>References</h3><p><a href="https://apidock.com/rails/ActiveRecord/Base/default_scope/class"><strong>Default_scope — </strong>Docs</a></p><p><a href="https://dev.to/lewuathe/why-we-should-avoid-defaultscope-in-rails-3ofo"><strong>Kai Sasaki — </strong>Why we should avoid default_scope</a></p><p><a href="https://stackoverflow.com/questions/25087336/why-is-using-the-rails-default-scope-often-recommend-against"><strong>StackOverflow — </strong>Great thread on this topic</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=eb260744f196" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/a-closer-look-at-rails-default-scope-eb260744f196">A Closer Look at Default_Scope</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Introduction to Rack middleware]]></title>
            <link>https://levelup.gitconnected.com/introduction-to-rack-middleware-97d87474632d?source=rss-146b58c03e1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/97d87474632d</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[tips-and-tricks]]></category>
            <dc:creator><![CDATA[Emir Vatric]]></dc:creator>
            <pubDate>Fri, 31 Jul 2020 11:34:50 GMT</pubDate>
            <atom:updated>2020-07-31T11:34:50.343Z</atom:updated>
            <content:encoded><![CDATA[<p>What is Rack and how can we use it?</p><p>Being on the beautiful journey that is Software Development, and working as a Rails Developer, I often get curious about the different building blocks of this beautiful framework. Whenever I get time I like to go deep on one of these subjects, read about it and try to understand them, how to use them, and leverage that knowledge into producing better apps.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1000/1*Ob-qS8GW6cHdhj1RNsiBhQ.png" /></figure><p>One of those important parts of Ruby on Rails certainly is Rack, and it is worth our time to go through. Learning about Rack, I have found more than a few excellent usages to better my skills and make my life easier.</p><h3><strong>What is Middleware?</strong></h3><p>This term gets used a lot, so much so that it is difficult to define it precisely but rather give it a few different definitions across the industry. We will try to focus on web development and usage of middleware mainly in Rails applications.</p><blockquote>Middleware is a (loosely defined) term for any software or service that enables the parts of a system to communicate and manage data. It is the software that handles communication between components and input/output, so developers can focus on the specific purpose of their application.</blockquote><p>In server-side web application frameworks like Ruby on Rails, this term is often used to refer to pre-build components or libraries like Rack middleware that can be added to the framework’s request/response processing pipeline in which data flows through a sequence of tasks or stages. Very common examples are logging, authentication, and the other, these tend to be the helpers that everyone needs across multiple applications, they basically intercept a request, do something with it and pass it on.</p><h3>What is Rack?</h3><p>Rack provides a minimal, modular, and adaptable interface for developing web applications in Ruby. By wrapping HTTP requests and responses in the simplest way possible, it unifies and distills the API for web servers, web frameworks, and software in between (the so-called middleware) into a single method call.</p><p>The characteristics of a Rack application is that the application object responds to the call method. The call method takes in the environment object as an argument and returns the Rack response object.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*dY3J04qvnnWpjid0fkRr-A.png" /></figure><p>In its core, it is important to understand that Rack is not just a request/response filter it does so much more, Rack is a web server interface convention, a modular interface between web servers and web applications developed in the Ruby programming language.</p><h4>Simple Rack App</h4><p>In order to get a better understanding let’s take this nice and simple Rack app and go through the code to see what it does.</p><p>We’ll use WEBrick as rack compliant webserver, but any of them will do. Let’s create a simple web application that returns a JSON string. First, we need to create a config.ru file inside our directory, in our config file, we will have the following code:</p><pre><strong>class Application<br> def</strong> <strong>call</strong>(env)<br>    status  <strong>=</strong> 200<br>    headers <strong>=</strong> { &quot;Content-Type&quot; <strong>=&gt;</strong> &quot;text/html&quot; }<br>    body    <strong>=</strong> [&quot;This is our small Rack app.&quot;]<br><br>    [status, headers, body]<br>  <strong>end</strong><br><strong>end</strong><br><br>run Application.<strong>new</strong></pre><p>Rack gem comes with little executable (command-line program) called rackup, so let&#39;s run it.</p><pre>$ rackup<br>[2015-05-15 18:37:42] INFO  WEBrick 1.3.1<br>[2015-05-15 18:37:42] INFO  ruby 2.2.1 (2015-02-26) [x86_64-darwin14]<br>[2015-05-15 18:37:42] INFO  WEBrick::HTTPServer#start: pid=17588 port=9292</pre><p>Now our web application has started we can point our browser to localhost:9292, and we should see textThis is our small Rack app.</p><p>In Ruby on Rails, for example, the Rack requests hit the ActionDispatch::Routing.Mapper and dependent on the env hash if any route matches it passes the env hash on to the application to compute the response, otherwise it immediately responds with a 404.</p><h3>Rack the gem</h3><p>Rack besides being a convention it is also a well-known gem, and it provides great functionality. In our aforementioned example, we have already used rackup command that comes with Rack gem.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/795/1*9tqQwmlNnO_Q_SgJxWfUJQ.jpeg" /></figure><p>Between the server and the framework, Rack can be customized to your application needs using middleware. Rack itself ships with quite a few middlewares from serving static files, setting default Content-Type header for responses to removing temporary files creating during a request. Please see the documentation for a detailed list of all <a href="https://github.com/rack/rack">middleware</a>.</p><h3>Community</h3><p>There is also a great community around Rack gem that produces pre-built Rack components that help you deal with tasks like Authentication, Authorization, Caching, Decoration and so much more. For a full list please visit the Rack official documentation on <a href="https://github.com/rack/rack/wiki/List-of-Middleware">Rack middleware</a>.</p><p>But while we are here let’s take a look at a few examples.</p><h4>SEO optimizations</h4><p>SEO stands for “search engine optimization.” It’s the practice of increasing both the quality and quantity of website traffic, as well as exposure to your brand, and these days it gets a lot of attention while building the products.</p><p>Recently my work buddy got the task to remove a trailing slash at the end of the URL, and we ware able to find a rescue in Rack component developed by its community.</p><p><a href="https://github.com/jtrupiano/rack-rewrite">Rack-rewrite</a> is rack middleware for defining and applying rewrite rules, and it is super easy to use, for our purpose all we needed to do is to install the gem and call it inside our Application.rb.</p><pre>config.middleware.insert_before(Rack::Runtime, Rack::Rewrite) do<br> r301 %r{^/(.*)/$}, ‘/$1’<br>end</pre><h4>Authentication</h4><p>Doing the authentication from scratch can be difficult, and can cause unforeseen issues. Here we can get a lot of help from another Rack middleware, <a href="https://github.com/wardencommunity/warden">Warden</a>, Warden provides a mechanism for authentication in Rack-based Ruby applications. It’s made with multiple applications sharing within the same rack instance in mind.</p><p>Warden is designed to be lazy. That is, if you don’t use it, it doesn’t do anything, but when you do use it, it will spring into action and provide an underlying mechanism to allow authentication in any Rack-based application.</p><h3>Conclusion</h3><p>When I started writing and reading about this topic I genuinely didn’t pay too much attention to the Rack, it is easy to take it for granted, but it makes our lives a lot easier.</p><p>While I am not a mad scientist, master, or senior I find it to be satisfying to write about topics in Rails, and especially about important parts of the Rails framework.</p><p>Hopefully, you will find this article interesting and helpful.</p><h3>References</h3><p><a href="https://github.com/rack/rack"><em>Official documentation</em></a></p><p><a href="https://stackoverflow.com/questions/2256569/what-is-rack-middleware"><em>This awesome StackOverflow thread</em></a></p><p><a href="https://webapps-for-beginners.rubymonstas.org/rack/hello_world.html">Rubymonsters topic on Rack</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=97d87474632d" width="1" height="1" alt=""><hr><p><a href="https://levelup.gitconnected.com/introduction-to-rack-middleware-97d87474632d">Introduction to Rack middleware</a> was originally published in <a href="https://levelup.gitconnected.com/">Level Up Coding</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding Rake in Ruby]]></title>
            <link>https://medium.com/swlh/understanding-rake-in-ruby-9eaf7f7b20cc?source=rss-146b58c03e1a------2</link>
            <guid isPermaLink="false">https://medium.com/p/9eaf7f7b20cc</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[rake]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Emir Vatric]]></dc:creator>
            <pubDate>Sat, 25 Jan 2020 19:26:02 GMT</pubDate>
            <atom:updated>2020-02-04T15:41:47.377Z</atom:updated>
            <content:encoded><![CDATA[<p>I am by no means a Rails or Ruby expert, but I was interested in what was happening when we call <strong><em>rake routes/rails routes </em></strong>or<strong> <em>rake db:migrate /rails db:migrate</em></strong>, so I decided to read up a little bit about rake and present it here.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/866/1*pkqkgccDaLUMeAYbqi7_GA.jpeg" /></figure><h3>What is Rake?</h3><p>Rake is a tool for organizing tasks, a task runner in Ruby or. Anyone who develops with Rails uses the Rake tool all the time. Rake will run your tests, migrate your database, precompile your assets, and more.</p><p>Let’s consider this example. We have a task to wash our hands:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/359/1*-uJpNvDWWsJlXlpHh1AF7A.jpeg" /></figure><p>Our task of washing hands consists of more mini-tasks (dependencies) that are building blocks of our main task, so to execute the main task we need to reference and execute our dependencies.</p><p>If we wrote this action as a rake file it would look something like this. Rake files we wright in ruby code, every task has a name, every task has an action encoded in do end block, and finally, tasks have dependencies.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KNQ7ltzk8vzex-zhyREuGw.png" /></figure><p>Now hopefully it is obvious what is going to happen when we run <strong><em>rake wash_hands</em></strong>, we will start executing our tasks:</p><pre>$rake wash_hands<br>Wet your hands<br>Soap your hands<br>Wash your hands<br>Rinse your hands<br>Dry your hands<br>Task is done your hands are clean</pre><p>Because tasks can have similar names, it’s easy to use the same name twice. That’s why Rake has namespaces. For example, we can have a namespace of a dog with tasks.</p><pre>namespace :dog do<br>  task :feed do<br>    ...<br>  end<br><br>  task :groom do<br>    ...<br>  end<br><br>  task :walk do<br>    ...<br>  end<br>end</pre><p>To run a namespaced task:</p><pre>rake dog:feed</pre><p>Also worth mentioning and providing are some useful Rake options:</p><ul><li>rake -T (list available tasks)</li><li>rake -P (list tasks &amp; their dependencies)</li><li>rake -W (list tasks &amp; where they are defined)</li><li>rake -V (verbose mode, echo system commands)</li><li>rake -t (debugging mode)</li><li>rake -f (use a specific Rakefile)</li></ul><p>There is a lot more to Rake but for our purposes, a basic intro into Rake will just do. At the bottom of the document, I linked a great lecture by late <strong>Jim Weirich</strong> about the subject, please check it out if you are interested in this topic.</p><h3>Rake in Ruby on Rails</h3><p>While watching Rails conference keynote on request lifecycle I have heard the expression ‘<em>everything is rake app</em>’ many times or if you have done any development in Rails than you have used Rake tasks. So let’s talk about them, and how can we leverage them.</p><p>Worth noting is that since Rails 5 core team decided to have consistency by enabling rails command to support everything that rake does. Some favor using rake over rails.</p><p>Don’t confuse Rake with <a href="https://www.rubyguides.com/2018/09/rack-middleware/">Rack</a>, very similar names, but completely different things.</p><ul><li><strong>Rake</strong> is a task runner.</li><li><strong>Rack</strong> helps Ruby servers &amp; frameworks work together.</li></ul><p>Let’s start by running a <strong><em>rake -T </em></strong>or<strong><em> rails -T </em></strong>in a console on our fresh Ruby on Rails project. This command should print the list of available tasks for us to run, and the result will look like this <em>(the list is truncated for space purposes)</em>.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*4yodi3j0md5iwRE-ys1B-A.png" /></figure><p>Here we can see and recognize some tasks that we run regularly like some under db namespace like <strong><em>db:migrate</em></strong> or <strong><em>db:rollback</em></strong>, but also we notice that some tasks are missing like <strong><em>rake routes</em></strong>. If instead of running rails -T we run rails -P we will notice them showing up.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/588/1*mImgQdw1poPg7Jc50FdlJw.png" /></figure><p>This happens because our routes task doesn&#39;t have a description that tasks above have. This is by design and not an accident.</p><p>Ok now we know that this is a rake task but where is it coming from, for this purpose rake gave us command <strong><em>rake -W [task name]</em></strong>, let’s try it out.</p><pre>$rake -W routes<br>...gems/ruby-2.6.0/gems/railties-6.0.2.1/lib/rails/tasks/routes.rake</pre><p>When running rake routes the part of code that is being executed is this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/590001820bbbb3e34ba7b1e40e32e04b/href">https://medium.com/media/590001820bbbb3e34ba7b1e40e32e04b/href</a></iframe><p>But rake is more useful than just running existing tasks, we can also write our own tasks in rails, those tasks should live in <strong><em>lib/tasks</em></strong>. But also Rake allows us to run multiple tasks in a single line, executing tasks one by one. This can be useful if we want to remove all the data from database, then create it again and run the migrations.</p><pre>$rake db:drop db:create db:migrate db:seed</pre><h3>Conclusion</h3><p>When I started writing and reading about this topic I genuinely didn’t pay too much attention to the Rake, it is easy to take it for granted, but it makes our lives a lot easier.</p><p>While I am not a mad scientist, master or senior I find it to be satisfying to write about topics in Rails, and especially about beautiful and simple to use tools like Rake.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*uhqnOqUOoU1ZUcOl5zRjJA.png" /></figure><h3><strong>References</strong></h3><p><a href="https://www.youtube.com/watch?v=AFPWDzHWjEY"><strong>Jim Weirich —</strong> Basic Rake</a></p><p><a href="https://www.youtube.com/watch?v=8HRJQUr2Y3Q"><strong>Barrett Clark — </strong>RailsConf 2016 — Crushing It With Rake Tasks</a></p><p><a href="https://www.rubyguides.com/2019/02/ruby-rake/"><strong>Jesus Castello — </strong>What is Rake in Ruby &amp; How to Use it</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=9eaf7f7b20cc" width="1" height="1" alt=""><hr><p><a href="https://medium.com/swlh/understanding-rake-in-ruby-9eaf7f7b20cc">Understanding Rake in Ruby</a> was originally published in <a href="https://medium.com/swlh">The Startup</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>