<?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 Egemen Öztürk on Medium]]></title>
        <description><![CDATA[Stories by Egemen Öztürk on Medium]]></description>
        <link>https://medium.com/@egemenn?source=rss-4c896e4e8235------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*SevpC7YNY_WMutnrOLhH1g.jpeg</url>
            <title>Stories by Egemen Öztürk on Medium</title>
            <link>https://medium.com/@egemenn?source=rss-4c896e4e8235------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Wed, 18 Nov 2026 09:45:08 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@egemenn/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[Breaking Changes Without Breaking Production | Rails 6.1 → 7.0]]></title>
            <link>https://blog.simprasuite.com/breaking-changes-without-breaking-production-rails-6-1-7-0-ac003efd1bd0?source=rss-4c896e4e8235------2</link>
            <guid isPermaLink="false">https://medium.com/p/ac003efd1bd0</guid>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[rails-7]]></category>
            <dc:creator><![CDATA[Egemen Öztürk]]></dc:creator>
            <pubDate>Tue, 30 Dec 2025 13:08:34 GMT</pubDate>
            <atom:updated>2025-12-30T13:08:34.995Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1004/1*meP_GNvZ8dlhYXUl5Cdd9g.png" /></figure><p>Upgrading a production Rails app is one of those tasks that can either be smooth and rewarding… or absolutely terrifying.</p><p>In short, it’s risky.</p><p>After completing our production upgrade from Rails <strong>6.1.7.10</strong> to <strong>7.0.8.7</strong>, I wanted to share the exact path that helped us ship this safely.</p><p>If you’re planning a Rails upgrade, this guide might save you many hours and probably some sanity.</p><h4><strong>1. Always Upgrade From Latest Patch to Latest Patch</strong></h4><p>Never jump versions blindly. Use the <em>foolproof</em> upgrade path.</p><p><strong>MAJOR.MINOR.PATCH</strong></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/480/0*efQaLmcnjLf4au_x.gif" /><figcaption>source: <a href="https://media4.giphy.com/media/v1.Y2lkPTc5MGI3NjExazZyOTFyejc0MGR0NmN3eHB4N2JvZm5uNmxnMGxubXU4NzdqcmJ2dCZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw/800iiDTaNNFOwytONV/giphy.gif">Giphy</a></figcaption></figure><p>Example:</p><pre>Rails 4.1 → 5.0<br><br>4.1.11 → 4.1.16 → 4.2.11.1 → 5.0.7.2</pre><p>Our Case: Rails 6.1 → 7.0</p><p>We were already on the latest Rails 6 patch:</p><pre>6.1.7.10 → 7.0.8.7</pre><p>This drastically reduces unknown breakage and allows you to rely on stable patch releases.</p><h4><strong>2. Ensure Gem Compatibility Early</strong></h4><p>Before touching the Rails version, make sure your entire gem ecosystem supports Rails 7.</p><p>If even one of your gems is not compatible, your upgrade will stall.<br>So we upgraded and fixed incompatible gems first, then upgraded Rails.</p><p>This step alone saves an enormous amount of time and frustration.</p><p><strong>My thoughts on testing</strong></p><blockquote>I was fortunate to upgrade a Rails application with a very solid test suite, and it saved us a massive amount of time while helping us catch issues early.</blockquote><blockquote>I think the early investment my team made in this project truly paid off .</blockquote><h4><strong>3. Heavy Automated Testing + Manual Testing</strong></h4><p>A successful upgrade is 99% testing.</p><p>What we did:</p><p>• Ran the entire automated test suite after each significant change<br>• Added missing coverage wherever breakage appeared<br>• Performed careful manual verification of critical user flows</p><p><strong>Important Changes Between 6.1.7.10 and 7.0.8.7</strong></p><ul><li><a href="https://guides.rubyonrails.org/v7.0/classic_to_zeitwerk_howto.html">Autoloader changed to Zeitwerk</a></li><li><a href="https://github.com/rails/rails/blob/de7c495209811f8f918fa9f915e64df61a6080c1/guides/source/7_0_release_notes.md#deprecations-8">to_s(:db) is deprecated use Time#to_fs(:db)</a></li><li><a href="https://github.com/rails/rails/commit/e3b9779cb701c63012bc1af007c71dc5a888d35a">Preloader now requires keyword arguments in Rails 7</a></li><li><a href="https://github.com/rails/rails/commit/afab1ef7c37a2d6a772c8f0c3a124313de816eb7">.find_by! errors now include the condition in the raised exception</a></li><li><a href="https://guides.rubyonrails.org/v7.2/upgrading_ruby_on_rails.html#sprockets-is-now-an-optional-dependency">Sprockets is now an optional dependency</a></li><li><a href="https://github.com/mileszs/wicked_pdf/issues/1005">Render partials path behavior change</a></li><li><a href="https://github.com/rails/rails/issues/45017">Silent rollback behavior inside transaction blocks</a> (!)</li></ul><p><strong>Useful Tools and Sites</strong></p><ul><li><a href="https://guides.rubyonrails.org/v7.2/upgrading_ruby_on_rails.html#upgrading-from-rails-6-1-to-rails-7-0">Official Rails upgrade guide</a></li><li><a href="https://guides.rubyonrails.org/v7.0/classic_to_zeitwerk_howto.html">Zeitwerk migration guide</a></li><li><a href="https://railsdiff.org/6.1.7.10/7.0.8.7">Rails version diff</a> (railsdiff)</li><li><a href="https://www.railsup.io/">Gem compatibility checker</a> (railsupio)</li><li><a href="https://thoughtbot.com/blog/upgrade-rails-6-to-rails-7">Thoughtbot’s Rails 7 upgrade article</a></li></ul><h4><strong>Final Thoughts</strong></h4><p>A Rails upgrade doesn’t have to be painful. It does require discipline, patience, and a serious commitment to <strong>testing</strong>.</p><p>If you respect the process and prepare your codebase properly, the upgrade becomes just another engineering task instead of a production nightmare.</p><p>Since Rails 8 is out, we are going to upgrade our application from Rails 7 to 8 soon.</p><p>Happy upgrading.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ac003efd1bd0" width="1" height="1" alt=""><hr><p><a href="https://blog.simprasuite.com/breaking-changes-without-breaking-production-rails-6-1-7-0-ac003efd1bd0">Breaking Changes Without Breaking Production | Rails 6.1 → 7.0</a> was originally published in <a href="https://blog.simprasuite.com/">Simpra Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Built Robust GraphQL APIs with Ruby on Rails and graphql-batch]]></title>
            <link>https://blog.simprasuite.com/built-robust-graphql-apis-with-ruby-on-rails-and-graphql-batch-ef5c1eafbeee?source=rss-4c896e4e8235------2</link>
            <guid isPermaLink="false">https://medium.com/p/ef5c1eafbeee</guid>
            <category><![CDATA[backend]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[graphql]]></category>
            <category><![CDATA[api]]></category>
            <dc:creator><![CDATA[Egemen Öztürk]]></dc:creator>
            <pubDate>Tue, 24 Jun 2025 14:22:08 GMT</pubDate>
            <atom:updated>2025-06-24T14:28:46.056Z</atom:updated>
            <content:encoded><![CDATA[<h3>Build Robust APIs using Ruby on Rails with GraphQL and graphql-batch</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*pLKoqIBKoeXb1kebiF8-5w.jpeg" /></figure><ul><li>Why GraphQL?</li><li>Setting Up a Rails 8 App with GraphQL</li><li>Implementing GraphQL Types</li><li>Implementing GraphQL Mutations</li><li>What is graphql-batch and What does it do?</li></ul><h3>Introduction</h3><p>GraphQL has become the de facto choice for modern API design when client flexibility and efficient data fetching are more than important then anything else. But its power comes with new considerations — most notably, how to prevent N+1 queries when dealing with nested relationships. This is where graphql-batch (from Shopify) steps in to help.</p><p>In this guide, we’ll go deep into implementing GraphQL in a Rails 8 API with graphql-batch, walk through a complete working CRUD example, and explore why GraphQL—when properly tuned—is a performance-optimized alternative to REST.</p><h3>Why GraphQL?</h3><h4>Potential Problems with REST APIs</h4><ul><li>Over-fetching: Clients get more data than they need.</li><li>Under-fetching: Multiple round-trips are needed to fetch related resources.</li><li>Rigid contracts: Evolving REST APIs can break consumers.</li></ul><h4>GraphQL Advantages</h4><ul><li>Clients specify <strong>exactly</strong> what data they need.</li><li>A single endpoint: /graphql replaces dozens of RESTful endpoints.</li><li>Nested queries naturally model relationships.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CWNSj5h_G8woRUVvq9bdzw.png" /><figcaption>REST vs GraphQL</figcaption></figure><h3>Setting Up a Rails 8 App with GraphQL</h3><p>Let’s create a simple blog application with authors and posts. Where each post belongs to an author. Our goal is to create a GraphQL API that allows clients to fetch authors and their posts.</p><h4>Step 1: Create a Rails 8 App</h4><pre>rails new blogverse --api --database=postgresql</pre><h4>Step 2: Install Gems</h4><pre># Gemfile<br><br>gem &#39;graphql&#39;        # GraphQL gem<br><br>gem &#39;graphiql-rails&#39; # GraphiQL gem (for testing in development)</pre><pre>bundle install</pre><h4>Step 3: Install GraphQL</h4><pre>rails generate graphql:install</pre><p>This sets up:</p><ul><li>/app/graphql/your_app_schema.rb</li><li>Base classes for Types and Mutations</li><li>A /graphql POST endpoint</li></ul><p>Then we will use graphiql-rails gem to test our GraphQL API. Add the following line to your config/routes.rb:</p><pre>mount GraphiQL::Rails::Engine, at: &quot;/graphiql&quot;, graphql_path: &quot;/graphql&quot;</pre><p>This will mount the GraphiQL query editor in a Rails app, so we can test our GraphQL API at http://localhost:3000/graphiql in our development environment.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*qE0z_xxS7BnHX5rU5ELahQ.png" /><figcaption>graphiql interface in localhost</figcaption></figure><p>Follow the <a href="https://github.com/rmosolgo/graphiql-rails">graphiql-rails official documentation</a> if you get stuck.</p><h4>Step 4: Generate Your Models and Migrations</h4><p>Let’s create a simple blog application with authors and posts. Where each post belongs to an author.</p><pre>rails g model Author name:string</pre><pre>rails g model Post title:string content:text author:references<br>rails db:migrate</pre><p>Your models files should look like this:</p><pre>class Author &lt; ApplicationRecord<br>  has_many :posts<br>end<br><br>class Post &lt; ApplicationRecord<br>  belongs_to :author<br>end</pre><p>This will create two models: Author and Post, with a has_many association between them.</p><p>And now, let’s create sample data:</p><pre># db/seeds.rb<br>(1..10).each do |author_id|<br>  author = Author.find_or_create_by!(id: author_id, name: &quot;Author #{author_id}&quot;)<br><br>  puts &quot;Author #{author_id} created&quot;<br><br>  (1..10).each do |post_id|<br>    Post.find_or_create_by!(id: &quot;#{author_id}#{post_id}&quot;, title: &quot;Post #{post_id}&quot;, content: &quot;Content #{post_id}&quot;) do |post|<br>      post.author = author<br>    end<br><br>    puts &quot;Post #{post_id} created for Author id: #{author_id}&quot;<br>  end<br><br>end<br><br>puts &quot;Seeds completed&quot;</pre><pre>rails db:seed</pre><h3>Implementing GraphQL Types</h3><p>GraphQL types define the shape of your data. Each ActiveRecord model usually maps to a Type.</p><pre># app/graphql/types/author_type.rb<br><br>module Types<br>  class AuthorType &lt; Types::BaseObject<br>    field :id, ID, null: false<br>    field :name, String, null: false<br>    # this tells GraphQL that the `posts` field returns an array of `PostType` objects<br>    field :posts, [ Types::PostType ], null: true<br>  end<br>end</pre><pre># app/graphql/types/post_type.rb<br><br>module Types<br>  class PostType &lt; Types::BaseObject<br>    field :id, ID, null: false<br>    field :title, String, null: false<br>    field :content, String, null: true<br><br>    # this tells GraphQL that the `author` field returns a `AuthorType` object<br>    field :author, Types::AuthorType, null: true<br>  end<br>end</pre><p>After defining the types, we should also define QueryTypes. It is used to query the data. You can think of it as registering a route to a controller action.</p><pre># app/graphql/types/query_type.rb<br><br>module Types<br>  class QueryType &lt; Types::BaseObject<br><br>    # When you query `posts` field, it hits the `posts` method below.<br>    field :posts, [ Types::PostType ], null: true, description: &quot;Fetches all posts.&quot; do<br>      argument :limit, Integer, required: false, description: &quot;Limit of the posts.&quot;, default_value: 10<br>    end<br><br>    def posts(limit:)<br>      Post.limit(limit)<br>    end<br><br>    field :authors, [ Types::AuthorType ], null: true, description: &quot;Fetches all authors.&quot; do<br>      argument :limit, Integer, required: false, description: &quot;Limit of the authors.&quot;, default_value: 10<br>    end<br><br>    def authors(limit:)<br>      Author.limit(limit)<br>    end<br>  end<br>end</pre><h3>Implementing GraphQL Mutations</h3><p>Mutations allow clients to modify data: create, update, delete.</p><h4>Create Post Mutation</h4><pre># app/graphql/mutations/create_post.rb<br><br>module Mutations<br>  class CreatePost &lt; BaseMutation<br>    argument :title, String, required: true<br>    argument :author_id, ID, required: true<br><br>    field :post, Types::PostType, null: true<br>    field :errors, [String], null: false<br><br>    def resolve(title:, author_id:)<br>      post = Post.new(title:, author_id:)<br>      if post.save<br>        { post:, errors: [] }<br>      else<br>        { post: nil, errors: post.errors.full_messages }<br>      end<br>    end<br>  end<br>end</pre><h4>Update Post Mutation</h4><pre># app/graphql/mutations/update_post.rb<br><br>module Mutations<br>  class UpdatePost &lt; BaseMutation<br>    argument :id, ID, required: true<br>    argument :title, String, required: true<br>    argument :author_id, ID, required: true<br><br>    field :post, Types::PostType, null: true<br>    field :errors, [String], null: false<br><br>    def resolve(id:, title:, author_id:)<br>      post = Post.find(id)<br>      post.update(title:, author_id:)<br>      if post.save<br>        { post:, errors: [] }<br>      else<br>        { post: nil, errors: post.errors.full_messages }<br>      end<br>    end<br>  end<br>end</pre><h4>Delete Post Mutation</h4><pre># app/graphql/mutations/delete_post.rb<br><br>module Mutations<br>  class DeletePost &lt; BaseMutation<br>    argument :id, ID, required: true<br><br>    field :post, Types::PostType, null: true<br>    field :errors, [String], null: false<br><br>    def resolve(id:)<br>      post = Post.find(id)<br>      post.destroy<br>      { post:, errors: [] }<br>    end<br>  end<br>end</pre><p>Wire it up in the Mutation Type:</p><pre># app/graphql/types/mutation_type.rb<br><br>module Types<br>  class MutationType &lt; Types::BaseObject<br>    field :create_post, mutation: Mutations::CreatePost<br>    field :update_post, mutation: Mutations::UpdatePost<br>    field :delete_post, mutation: Mutations::DeletePost<br>  end<br>end</pre><h4>CRUD Example</h4><p>Now let’s test our CRUD operations. Open http://localhost:3000/graphiql in your browser and try the following queries:</p><h4>Query Example</h4><pre>query {<br>  authors {<br>    name<br>    posts {<br>      title<br>    }<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*MMcY8qMZ-4OIIuKVKKEmQw.png" /><figcaption>graphiql query example in browser</figcaption></figure><h4>Mutation Example</h4><pre>mutation {<br>  createPost(input: { title: &quot;New Post&quot;, authorId: 1 }) {<br>    post {<br>      title<br>    }<br>    errors<br>  }<br>}<br><br>mutation {<br>  updatePost(input: { id: 1, authorId: 1, title: &quot;Updated Post&quot; }) {<br>    post {<br>      title<br>    }<br>    errors<br>  }<br>}<br><br>mutation {<br>  deletePost(input: { id: 1 }) {<br>    post {<br>      id<br>    }<br>    errors<br>  }<br>}</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*7dJZlweOP91SAlCXxfJEag.png" /><figcaption>graphiql mutation example in browser</figcaption></figure><h3>What is graphql-batch and What does it do?</h3><blockquote>graphql-batch is a query batching executor for the graphql gem.</blockquote><h4>Example 1:</h4><p>Let’s take a look at a nested query where we are fetching authors and their posts. Let’s see two examples:</p><p>Without using graphql-batch, this would trigger 🐌 ❌:</p><pre>query {<br>  authors(limit: 5) {<br>    name<br>    posts {<br>      title<br>    }<br>  }<br>}</pre><ul><li>1 query to fetch all authors</li><li>N queries to fetch posts for each author → <strong>N+1 queries</strong></li></ul><p>Example log without using graphql-batch:</p><pre>Author Load (1.0ms)  SELECT &quot;authors&quot;.* FROM &quot;authors&quot; LIMIT 3 /*action=&#39;execute&#39;,application=&#39;Blogverse&#39;,controller=&#39;graphql&#39;,current_graphql_field=&#39;Query.authors&#39;*/<br>  ↳ app/controllers/graphql_controller.rb:17:in &#39;GraphqlController#execute&#39;<br>  Post Load (0.0ms)  SELECT &quot;posts&quot;.* FROM &quot;posts&quot; WHERE &quot;posts&quot;.&quot;author_id&quot; = 1 /*action=&#39;execute&#39;,application=&#39;Blogverse&#39;,controller=&#39;graphql&#39;,current_graphql_field=&#39;Author.posts&#39;*/<br>  ↳ app/controllers/graphql_controller.rb:17:in &#39;GraphqlController#execute&#39;<br>  Post Load (0.0ms)  SELECT &quot;posts&quot;.* FROM &quot;posts&quot; WHERE &quot;posts&quot;.&quot;author_id&quot; = 2 /*action=&#39;execute&#39;,application=&#39;Blogverse&#39;,controller=&#39;graphql&#39;,current_graphql_field=&#39;Author.posts&#39;*/<br>  ↳ app/controllers/graphql_controller.rb:17:in &#39;GraphqlController#execute&#39;<br>  Post Load (0.0ms)  SELECT &quot;posts&quot;.* FROM &quot;posts&quot; WHERE &quot;posts&quot;.&quot;author_id&quot; = 3 /*action=&#39;execute&#39;,application=&#39;Blogverse&#39;,controller=&#39;graphql&#39;,current_graphql_field=&#39;Author.posts&#39;*/<br>  ↳ app/controllers/graphql_controller.rb:17:in &#39;GraphqlController#execute&#39;<br>  Post Load (0.0ms)  SELECT &quot;posts&quot;.* FROM &quot;posts&quot; WHERE &quot;posts&quot;.&quot;author_id&quot; = 4 /*action=&#39;execute&#39;,application=&#39;Blogverse&#39;,controller=&#39;graphql&#39;,current_graphql_field=&#39;Author.posts&#39;*/<br>  ↳ app/controllers/graphql_controller.rb:17:in &#39;GraphqlController#execute&#39;<br>  Post Load (0.0ms)  SELECT &quot;posts&quot;.* FROM &quot;posts&quot; WHERE &quot;posts&quot;.&quot;author_id&quot; = 5 /*action=&#39;execute&#39;,application=&#39;Blogverse&#39;,controller=&#39;graphql&#39;,current_graphql_field=&#39;Author.posts&#39;*/<br>  ↳ app/controllers/graphql_controller.rb:17:in &#39;GraphqlController#execute&#39;<br>Completed 200 OK in 68ms (Views: 0.1ms | ActiveRecord: 1.4ms (6 queries, 0 cached) | GC: 0.0ms)</pre><p>However, with graphql-batch, this would trigger 🚗 ✅:</p><ul><li>1 query to fetch all authors</li><li>1 query to fetch all posts for the authors</li></ul><p>Example log with using graphql-batch:</p><pre>Author Load (3.1ms)  SELECT &quot;authors&quot;.* FROM &quot;authors&quot; LIMIT 3 /*action=&#39;execute&#39;,application=&#39;Blogverse&#39;,controller=&#39;graphql&#39;,current_graphql_field=&#39;Query.authors&#39;*/<br>  ↳ app/controllers/graphql_controller.rb:17:in &#39;GraphqlController#execute&#39;<br>  Post Load (0.2ms)  SELECT &quot;posts&quot;.* FROM &quot;posts&quot; WHERE &quot;posts&quot;.&quot;author_id&quot; IN (1, 2, 3, 4, 5) /*action=&#39;execute&#39;,application=&#39;Blogverse&#39;,controller=&#39;graphql&#39;,current_graphql_field=&#39;Author.posts&#39;*/<br>  ↳ app/graphql/loaders/association_loader.rb:40:in &#39;Loaders::AssociationLoader#preload_association&#39;<br>Completed 200 OK in 98ms (Views: 0.1ms | ActiveRecord: 3.6ms (2 queries, 0 cached) | GC: 0.0ms)</pre><p>As you can see, the number of queries has been reduced to 2.</p><h4>Example 2:</h4><p>Let’s take a look at another nested query example where we are fetching posts and their authors.</p><p>Without using graphql-batch, this would trigger 🐌 ❌:</p><pre>query {<br>  posts(limit: 5) {<br>    title<br>    author{<br>      name<br>    }<br>  }<br>}</pre><ul><li>1 query to fetch all posts</li><li>N queries to fetch authors for each post → <strong>N+1 queries</strong></li></ul><p>Example log without using graphql-batch:</p><pre>Post Load (0.1ms)  SELECT &quot;posts&quot;.* FROM &quot;posts&quot; LIMIT 3 /*action=&#39;execute&#39;,application=&#39;Blogverse&#39;,controller=&#39;graphql&#39;,current_graphql_field=&#39;Query.posts&#39;*/<br>  ↳ app/controllers/graphql_controller.rb:17:in &#39;GraphqlController#execute&#39;<br>  Author Load (0.0ms)  SELECT &quot;authors&quot;.* FROM &quot;authors&quot; WHERE &quot;authors&quot;.&quot;id&quot; = 1 LIMIT 1 /*action=&#39;execute&#39;,application=&#39;Blogverse&#39;,controller=&#39;graphql&#39;,current_graphql_field=&#39;Post.author&#39;*/<br>  ↳ app/controllers/graphql_controller.rb:17:in &#39;GraphqlController#execute&#39;<br>  CACHE Author Load (0.0ms)  SELECT &quot;authors&quot;.* FROM &quot;authors&quot; WHERE &quot;authors&quot;.&quot;id&quot; = 1 LIMIT 1<br>  ↳ app/controllers/graphql_controller.rb:17:in &#39;GraphqlController#execute&#39;<br>  CACHE Author Load (0.0ms)  SELECT &quot;authors&quot;.* FROM &quot;authors&quot; WHERE &quot;authors&quot;.&quot;id&quot; = 1 LIMIT 1<br>  ↳ app/controllers/graphql_controller.rb:17:in &#39;GraphqlController#execute&#39;<br>  CACHE Author Load (0.0ms)  SELECT &quot;authors&quot;.* FROM &quot;authors&quot; WHERE &quot;authors&quot;.&quot;id&quot; = 1 LIMIT 1<br>  ↳ app/controllers/graphql_controller.rb:17:in &#39;GraphqlController#execute&#39;<br>  CACHE Author Load (0.0ms)  SELECT &quot;authors&quot;.* FROM &quot;authors&quot; WHERE &quot;authors&quot;.&quot;id&quot; = 1 LIMIT 1<br>  ↳ app/controllers/graphql_controller.rb:17:in &#39;GraphqlController#execute&#39;<br>  CACHE Author Load (0.0ms)  SELECT &quot;authors&quot;.* FROM &quot;authors&quot; WHERE &quot;authors&quot;.&quot;id&quot; = 1 LIMIT 1<br>  ↳ app/controllers/graphql_controller.rb:17:in &#39;GraphqlController#execute&#39;<br>Completed 200 OK in 66ms (Views: 0.1ms | ActiveRecord: 0.1ms (6 queries, 5 cached) | GC: 4.5ms)</pre><p>However, with using graphql-batch, this would trigger 🚗 ✅:</p><ul><li>1 query to fetch all posts</li><li>1 query to fetch all authors for the posts</li></ul><p>Example log with using graphql-batch:</p><pre>Post Load (0.8ms)  SELECT &quot;posts&quot;.* FROM &quot;posts&quot; LIMIT 3 /*action=&#39;execute&#39;,application=&#39;Blogverse&#39;,controller=&#39;graphql&#39;,current_graphql_field=&#39;Query.posts&#39;*/<br>  ↳ app/controllers/graphql_controller.rb:17:in &#39;GraphqlController#execute&#39;<br>  Author Load (0.0ms)  SELECT &quot;authors&quot;.* FROM &quot;authors&quot; WHERE &quot;authors&quot;.&quot;id&quot; = 1 /*action=&#39;execute&#39;,application=&#39;Blogverse&#39;,controller=&#39;graphql&#39;,current_graphql_field=&#39;Post.author&#39;*/<br>  ↳ app/graphql/loaders/record_loader.rb:8:in &#39;Loaders::RecordLoader#perform&#39;<br>Completed 200 OK in 72ms (Views: 0.1ms | ActiveRecord: 1.2ms (2 queries, 0 cached) | GC: 0.9ms)</pre><p>As you can see, the number of queries has been reduced to 2.</p><h3>Fixing N+1 Problems with graphql-batch</h3><h4>Step 1: Include GraphQL::Batch in your schema</h4><pre>bundle add &#39;graphql-batch&#39;</pre><pre># app/graphql/your_app_schema.rb<br><br>class YourAppSchema &lt; GraphQL::Schema<br>  use GraphQL::Batch<br>  query Types::QueryType<br>  mutation Types::MutationType<br>end</pre><h4>Step 2: Create a Loader Module</h4><p>We are going to create two loader modules: AssociationLoader and RecordLoader.</p><ul><li>AssociationLoader -&gt; Loads associations for a given model.</li><li>RecordLoader -&gt; Loads a single record for a given model.</li></ul><p>Lets use official examples from <a href="https://github.com/Shopify/graphql-batch">graphql-batch</a> gem. Loaders should look like this as per the <a href="https://github.com/Shopify/graphql-batch/blob/main/examples">graphql-batch official documentation</a>.</p><pre># app/graphql/loaders/association_loader.rb<br><br>module Loaders<br>  class AssociationLoader &lt; GraphQL::Batch::Loader<br>    def self.validate(model, association_name)<br>      new(model, association_name)<br>      nil<br>    end<br><br>    def initialize(model, association_name)<br>      super()<br>      @model = model<br>      @association_name = association_name<br>      validate<br>    end<br><br>    def load(record)<br>      raise TypeError, &quot;#{@model} loader can&#39;t load association for #{record.class}&quot; unless record.is_a?(@model)<br>      return Promise.resolve(read_association(record)) if association_loaded?(record)<br>      super<br>    end<br><br>    # We want to load the associations on all records, even if they have the same id<br>    def cache_key(record)<br>      record.object_id<br>    end<br><br>    def perform(records)<br>      preload_association(records)<br>      records.each { |record| fulfill(record, read_association(record)) }<br>    end<br><br>    private<br><br>    def validate<br>      unless @model.reflect_on_association(@association_name)<br>        raise ArgumentError, &quot;No association #{@association_name} on #{@model}&quot;<br>      end<br>    end<br><br>    def preload_association(records)<br>      ::ActiveRecord::Associations::Preloader.new(records: records, associations: @association_name).call<br>    end<br><br>    def read_association(record)<br>      record.public_send(@association_name)<br>    end<br><br>    def association_loaded?(record)<br>      record.association(@association_name).loaded?<br>    end<br>  end<br>end</pre><pre># app/graphql/loaders/record_loader.rb<br><br>module Loaders<br>  class RecordLoader &lt; GraphQL::Batch::Loader<br>    def initialize(model, column: model.primary_key, where: nil)<br>      super()<br>      @model = model<br>      @column = column.to_s<br>      @column_type = model.type_for_attribute(@column)<br>      @where = where<br>    end<br><br>    def load(key)<br>      super(@column_type.cast(key))<br>    end<br><br>    def perform(keys)<br>      query(keys).each { |record| fulfill(record.public_send(@column), record) }<br>      keys.each { |key| fulfill(key, nil) unless fulfilled?(key) }<br>    end<br><br>    private<br><br>    def query(keys)<br>      scope = @model<br>      scope = scope.where(@where) if @where<br>      scope.where(@column =&gt; keys)<br>    end<br>  end<br>end</pre><h4>Step 3: Using the Loader</h4><pre># app/graphql/types/author_type.rb<br><br>field :posts, [ Types::PostType ], null: true<br><br>def posts<br>  Loaders::AssociationLoader.for(Author, :posts).load(object)<br>end</pre><p>AssociationLoader is used to load associations for a given model. In our case, it loads the posts for each author.</p><pre># app/graphql/types/post_type.rb<br><br>field :author, Types::AuthorType, null: true<br><br>def author<br>  Loaders::RecordLoader.for(Author).load(object.author_id)<br>end</pre><p>RecordLoader is used to load a single record for a given model. In our case, it loads the author for each post.</p><h3>Conclusion</h3><p>GraphQL gives your clients flexible, efficient access to your data. But when not paired with tools like graphql-batch, it can fall into classic performance pitfalls like N+1 queries. With graphql-batch, Rails APIs become scalable, elegant, and performant.</p><p>In short:</p><ul><li>Use graphql-ruby to build your GraphQL API.</li><li>Use graphiql-rails to test your GraphQL API.</li><li>Use graphql-batch to resolve associations efficiently and eleminate N+1 queries.</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ef5c1eafbeee" width="1" height="1" alt=""><hr><p><a href="https://blog.simprasuite.com/built-robust-graphql-apis-with-ruby-on-rails-and-graphql-batch-ef5c1eafbeee">Built Robust GraphQL APIs with Ruby on Rails and graphql-batch</a> was originally published in <a href="https://blog.simprasuite.com/">Simpra Tech</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Decorator Pattern in Ruby]]></title>
            <link>https://medium.com/@egemenn/decorator-pattern-in-ruby-4c7162beeea7?source=rss-4c896e4e8235------2</link>
            <guid isPermaLink="false">https://medium.com/p/4c7162beeea7</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[design-patterns]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Egemen Öztürk]]></dc:creator>
            <pubDate>Sat, 10 Aug 2024 17:19:33 GMT</pubDate>
            <atom:updated>2024-08-10T17:19:33.415Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*bn3JFdcXAF-0PuApd_DeLw.png" /><figcaption>Design Patterns: Decorator Pattern in Ruby</figcaption></figure><p>In object-oriented programming, the decorator pattern allows behaviour to be added to individual objects, without affecting the behaviour of other objects from the same class.</p><h3>It’s one of the design patterns</h3><p>A design pattern in software engineering is a proven solution to a common coding problem. It’s a way of organizing code that makes it more efficient, reusable, and easier to maintain. Essentially, it’s a template for structuring your code.</p><h3>Decorator pattern in Ruby</h3><p>Decorator pattern is particularly useful in Ruby for enhancing objects with additional methods. Ruby’s standard library provides the `SimpleDelegator` class to achieve this.</p><h3>What is SimpleDelegator?</h3><p>`SimpleDelegator` is a class from Ruby’s standard library that provides delegation. It works by wrapping an object and delegating method calls to the wrapped object. This allows us to extend the functionality of the wrapped object without altering its original implementation.</p><h3>Example: Decorating a Book Class</h3><p>Let’s look at a very simple example using a Book class and a decorator.</p><pre>class Book<br>  attr_reader :title, :author<br><br>  def initialize(title, author)<br>    @title = title<br>    @author = author<br>  end<br><br>  def description<br>    &quot;#{title} by #{author}&quot;<br>  end<br>end<br><br>#####<br><br>class BookDecorator &lt; SimpleDelegator<br>  def fancy_description<br>    &quot;*** #{description} ***&quot;<br>  end<br>end</pre><p>In this example:</p><p>We got 2 things going on.</p><p>1. Book is a basic class with title and author attributes and a `#description` method.</p><p>2. BookDecorator extends SimpleDelegator and adds a `#fancy_description` method that introduces new behavior without altering the original Book class.</p><h3>Using the Decorator</h3><pre>book = Book.new(&#39;1984&#39;, &#39;George Orwell&#39;)<br><br># Decorate the book object here<br>decorated_book = BookDecorator.new(book)<br><br>decorated_book.description<br># =&gt; &quot;1984 by George Orwell&quot;<br><br>decorated_book.fancy_description<br># =&gt; &quot;*** 1984 by George Orwell ***&quot;</pre><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=4c7162beeea7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Efficient Querying in Rails: A Deep Dive into includes, preload, eager_load, and joins]]></title>
            <link>https://medium.com/@egemenn/efficient-querying-in-rails-a-deep-dive-into-includes-preload-eager-load-and-joins-dfe02a4e4725?source=rss-4c896e4e8235------2</link>
            <guid isPermaLink="false">https://medium.com/p/dfe02a4e4725</guid>
            <category><![CDATA[sql]]></category>
            <category><![CDATA[rails-api]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[software-engineering]]></category>
            <dc:creator><![CDATA[Egemen Öztürk]]></dc:creator>
            <pubDate>Sun, 30 Jun 2024 17:00:11 GMT</pubDate>
            <atom:updated>2024-07-24T18:45:43.311Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/801/1*e49VCz5K7eyUOQU_N94KEA.png" /></figure><p>In Ruby on Rails, includes, preload, eager_load and joins are powerful ActiveRecord query methods. These query methods are often used to optimize data loading and prevent N+1 query problems. However, the way they work under the hood is not the same. Here&#39;s a detailed explanation of what happens with each method.</p><h3>TL;DR</h3><p>Each method serves different purposes:</p><ul><li>eager_load fetches all associated records in a single query, <strong>ideal</strong> for reducing N+1 query issues.</li><li>preload issues separate queries to preload associations, <strong>ideal</strong> for reducing N+1 query issues.</li><li>joins performs an inner join to filter results based on specified conditions, useful for fetching filtered datasets efficiently, <strong>not ideal</strong> for reducing N+1 query issues.</li><li>includes it will decide if it&#39;ll use eager_load or preload under the hood, <strong>ideal</strong> for reducing N+1 query issues.</li></ul><h4>Example Structure:</h4><blockquote><em>We have a User model that can have many ShortPost and LongPost.</em></blockquote><h3>includes</h3><p>includes is dynamic. It is a shorthand for eager_load and preload. It will either generate a single LEFT OUTTER JOIN like eager_load (e.g., if you have a where clause that references a relationship) or loop over every association and generate separate query for each just like preload.</p><h3>eager_load</h3><pre>users = User.eager_load(:short_posts, :long_posts)</pre><p>This will generate SQL query similar to the following:</p><pre>SELECT DISTINCT &quot;users&quot;.&quot;id&quot; FROM &quot;users&quot;<br>LEFT OUTER JOIN &quot;short_posts&quot; ON &quot;short_posts&quot;.&quot;user_id&quot; = &quot;users&quot;.&quot;id&quot;<br>LEFT OUTER JOIN &quot;long_posts&quot; ON &quot;long_posts&quot;.&quot;user_id&quot; = &quot;users&quot;.&quot;id&quot;<br><br>SELECT &quot;users&quot;.&quot;id&quot; AS t0_r0, &quot;users&quot;.&quot;name&quot; AS t0_r1, &quot;users&quot;.&quot;created_at&quot; AS t0_r2, &quot;users&quot;.&quot;updated_at&quot; AS t0_r3,<br>       &quot;short_posts&quot;.&quot;id&quot; AS t1_r0, &quot;short_posts&quot;.&quot;user_id&quot; AS t1_r1, &quot;short_posts&quot;.&quot;created_at&quot; AS t1_r2,<br>       &quot;short_posts&quot;.&quot;updated_at&quot; AS t1_r3, &quot;short_posts&quot;.&quot;published&quot; AS t1_r4, &quot;long_posts&quot;.&quot;id&quot; AS t2_r0,<br>       &quot;long_posts&quot;.&quot;user_id&quot; AS t2_r1, &quot;long_posts&quot;.&quot;created_at&quot; AS t2_r2, &quot;long_posts&quot;.&quot;updated_at&quot; AS t2_r3, &quot;long_posts&quot;.&quot;published&quot; AS t2_r4 <br><br>FROM &quot;users&quot;<br>LEFT OUTER JOIN &quot;short_posts&quot; ON &quot;short_posts&quot;.&quot;user_id&quot; = &quot;users&quot;.&quot;id&quot;<br>LEFT OUTER JOIN &quot;long_posts&quot; ON &quot;long_posts&quot;.&quot;user_id&quot; = &quot;users&quot;.&quot;id&quot;<br>WHERE &quot;users&quot;.&quot;id&quot; IN (?, ?, ?, ?, ?)</pre><p>eager_load generates single query joining all specified associations at once with left outter join and loads User, ShortPost and LongPost records to the memory. This might cause an effincency problem if the datasets you are querying is huge.</p><p>Because this query will return all records from the left table, regardless of whether they have a match in the right table, along with any matching records from the right table, it’s better to be cautious.</p><h3>preload</h3><pre>users = User.preload(:short_posts, :long_posts)</pre><p>This will generate SQL query similar to the following:</p><pre>SELECT &quot;users&quot;.* FROM &quot;users&quot;<br>SELECT &quot;short_posts&quot;.* FROM &quot;short_posts&quot; WHERE &quot;short_posts&quot;.&quot;user_id&quot; IN (?, ?, ?, ?, ?)<br>SELECT &quot;long_posts&quot;.* FROM &quot;long_posts&quot; WHERE &quot;long_posts&quot;.&quot;user_id&quot; IN (?, ?, ?, ?, ?)</pre><p>preload generates separate queries for each specified association and loads User, ShortPost and LongPost records to the memory.</p><h3>joins</h3><pre>users = User.joins(:short_posts, :long_posts)<br>            .where(short_posts: { published: true }, long_posts: { published: false })</pre><p>This will generate SQL query similar to the following:</p><pre>SELECT &quot;users&quot;.*<br>FROM &quot;users&quot;<br>INNER JOIN &quot;short_posts&quot; ON &quot;short_posts&quot;.&quot;user_id&quot; = &quot;users&quot;.&quot;id&quot;<br>INNER JOIN &quot;long_posts&quot; ON &quot;long_posts&quot;.&quot;user_id&quot; = &quot;users&quot;.&quot;id&quot;<br>WHERE &quot;short_posts&quot;.&quot;published&quot; = 1 AND &quot;long_posts&quot;.&quot;published&quot; = 0;</pre><p>joins uses simple INNER JOIN and does not load associated records to the memory, meaning that it will trigger N+1 if you try to access associated data columns. However, it&#39;s handy for building conditional queries for specific data matching and filtering.</p><p><em>Originally published at </em><a href="https://egemen-dev.github.io/2024/06/30/efficient_querying_in_rails.html"><em>https://egemen-dev.github.io</em></a><em> on June 30, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dfe02a4e4725" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Size, Count, and Length Walk into a Rails App: Who Wins?]]></title>
            <link>https://medium.com/@egemenn/size-count-and-length-walk-into-a-rails-app-who-wins-2cf5b2a8fbe7?source=rss-4c896e4e8235------2</link>
            <guid isPermaLink="false">https://medium.com/p/2cf5b2a8fbe7</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[rails-7]]></category>
            <category><![CDATA[development]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[Egemen Öztürk]]></dc:creator>
            <pubDate>Mon, 06 May 2024 17:00:08 GMT</pubDate>
            <atom:updated>2024-07-15T09:28:05.898Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*jzbPbdK7EMlF4AqXliOe1g.jpeg" /></figure><p>In Ruby on Rails we got three similar looking methods count(), length() and size(). Let&#39;s see what they do under the hood.</p><p>Consider we got a variable that holds all the users.</p><pre>users = User.all</pre><h3>COUNT</h3><pre>users.count<br><br>  =&gt; SELECT COUNT(*) FROM &quot;users&quot;</pre><p>count() always performs SQL COUNT query, no matter how many times you call it.</p><h3>LENGTH</h3><pre>users.length<br><br>  =&gt; SELECT &quot;users&quot;.* FROM &quot;users&quot;</pre><p>length() checks if the data is present in the memory. If not, it loads the users data to the memory via SQL query and then calculates how many records are in the collection - no additional query gets executed to get the size of the collection. Note that it is not going to perform another SQL query next time you call it because the data is already stored in the memory. It&#39;s only going to output the size of the collection. So, it might come in handy if you&#39;re going to use the data later on.</p><h3>SIZE</h3><pre>users.size<br><br>  =&gt; SELECT COUNT(*) FROM &quot;users&quot;</pre><p>size() will check if the data is present in the memory. If the data is present, it calculates the size of the collection like lenght(). Otherwise it performs an SQL COUNT query.</p><h3>TAKE AWAY 🍔</h3><p>Winner is the Rails. size() and length() methods are distinguished when the data is not present in the memory. size() performs SQL COUNT query in order to give you the result while length() loads the data via SQL query, stores it in the memory and then outputs the size of the collection. Their behaviours are equivalent when the data is already loaded.</p><p>Source: <a href="https://api.rubyonrails.org/">rails api docs</a></p><p><em>Originally published at </em><a href="https://egemen-dev.github.io/2024/05/06/size-count-length.html"><em>https://egemen-dev.github.io</em></a><em> on May 6, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=2cf5b2a8fbe7" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What causes double render and how to prevent it?]]></title>
            <link>https://medium.com/@egemenn/what-causes-double-render-and-how-to-prevent-it-ebe69c6fc8c8?source=rss-4c896e4e8235------2</link>
            <guid isPermaLink="false">https://medium.com/p/ebe69c6fc8c8</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[rails-controllers]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Egemen Öztürk]]></dc:creator>
            <pubDate>Fri, 01 Mar 2024 17:00:39 GMT</pubDate>
            <atom:updated>2024-07-15T09:22:20.204Z</atom:updated>
            <content:encoded><![CDATA[<p>In ruby on rails backend development, developers might face a common situation captured in the following code snippet:</p><pre>def action<br>  check_params<br><br>  render json: { message: &quot;Action method worked, it&#39;s all good!&quot; }, status: 200<br>end<br><br>def check_params<br>  if params[:important_param] == &quot;&quot;<br>    render json: { error: &quot;Important param is missing&quot; }, status: 404<br>    <br>    return<br>  end<br>end</pre><h3>Purpose</h3><p>Basically, code is set up in a way that check the input params before the action method and avoid certain situations by stopping the execution right after the condition inside the check_params method is met. However, this is not happening and you get AbstractController::DoubleRenderError. The problem is that the check_params method is not stoppig the execution with 404 error response.</p><h3>Breaking down the problem</h3><p>The reason for the double rendering error here is because the check_params method&#39;s return statement is only exiting from the current method which is itself and not the entire action so that it reaches to the bottom of the action method and renders whatever is set to render, and you get yourself a nice double render error AbstractController::DoubleRenderError. This error indicates that there are multiple renders called in this particular action.</p><h3>Solution</h3><p>before_action ✅</p><p>Official Rails <a href="https://api.rubyonrails.org/v7.1.3.2/classes/AbstractController/Callbacks/ClassMethods.html#method-i-before_action">doc</a> says about the before_action:</p><blockquote><em>Append a callback before actions. If the callback </em><strong><em>renders</em></strong><em> or redirects, the action </em>will not run<em>. If there are additional callbacks scheduled to run after that callback, </em><strong><em>they are also cancelled</em></strong><em>.</em></blockquote><p>This is the exact behaviour the code should have.</p><p>Lets’s refactor the code in order to utilise the before_action callback:</p><pre>before_action :check_params, only: :action<br><br>def action<br>  render json: { message: &quot;Action method worked, it&#39;s all good!&quot; }, status: 200<br>end<br><br>def check_params<br>  if params[:important_param] == &quot;&quot;<br>    render json: { error: &quot;Important param is missing&quot; }, status: 404<br>    <br>    return<br>  end<br>end</pre><p><em>Originally published at </em><a href="https://egemen-dev.github.io/2024/03/01/what-is-double-render.html"><em>https://egemen-dev.github.io</em></a><em> on March 1, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ebe69c6fc8c8" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Leveraging Service Objects and Concerns in Refactoring Rails Model Callbacks]]></title>
            <link>https://medium.com/@egemenn/leveraging-service-objects-and-concerns-in-refactoring-rails-model-callbacks-db33cb041591?source=rss-4c896e4e8235------2</link>
            <guid isPermaLink="false">https://medium.com/p/db33cb041591</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[software-development]]></category>
            <category><![CDATA[refactoring]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Egemen Öztürk]]></dc:creator>
            <pubDate>Sat, 06 Jan 2024 17:00:00 GMT</pubDate>
            <atom:updated>2024-07-15T09:19:25.584Z</atom:updated>
            <content:encoded><![CDATA[<p>Active Record callbacks in Rails are a double-edged sword, offering automation while potentially leading to tangled code. Knowing when to use them and when to avoid them is crucial bacuse they are powerful. Read more about ActiveRecord Callbacks from the <a href="https://edgeguides.rubyonrails.org/active_record_callbacks.html">official docs</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/298/1*bweggtsM-AkccHjEqDnphA.gif" /></figure><h3>Leveraging Active Record Callbacks</h3><ul><li>Streamlined Workflows: Utilize callbacks for sequential tasks in an object’s life cycle, such as encrypting passwords or updating caches, ensuring a smoother operational flow.</li><li>Enhanced Code Organization: Utilize callbacks, potentially in tandem with ActiveRecord Concerns, to effectively consolidate repetitive tasks across diverse models, fostering code readability.</li><li>Centralized External Interactions: Employ callbacks to centralize interactions with external services, preventing code scattering and promoting a more structured approach.</li></ul><h3>Cautionary Measures</h3><ul><li>Combatting Complexity: Over-reliance on callbacks can obfuscate code flow, leading to challenges in debugging and comprehension.</li><li>Unforeseen Impacts: Callbacks might inadvertently trigger unintended side effects, especially when altering associated models.</li><li>Testing and Maintenance Hurdles: Extensive callback usage can complicate testing procedures and make maintenance a daunting task.</li></ul><h3>Callback Usage Examples:</h3><p>Example — Fictional code example with multiple callbacks</p><pre>class Order &lt; ApplicationRecord<br>  belongs_to :user<br><br>  after_create :send_order_confirmation_email<br>  after_save :update_user_activity_log<br>  after_commit :generate_invoice_pdf, on: [:create]<br><br>  # list goes on...<br>  <br>  private<br>  <br>  def send_order_confirmation_email<br>    # Send confirmation email logic...<br>    # Send confirmation email logic...<br>    # Send confirmation email logic...<br>    # Send confirmation email logic...<br>    # Send confirmation email logic...<br>  end<br>  <br>  def update_user_activity_log<br>    # Update user&#39;s activity log logic...<br>    # Update user&#39;s activity log logic...<br>    # Update user&#39;s activity log logic...<br>    # Update user&#39;s activity log logic...<br>    # Update user&#39;s activity log logic...<br>  end<br>  <br>  def generate_invoice_pdf<br>    # Generate invoice PDF logic...<br>    # Generate invoice PDF logic...<br>    # Generate invoice PDF logic...<br>    # Generate invoice PDF logic...<br>    # Generate invoice PDF logic...<br>    # Generate invoice PDF logic...<br>  end<br>end</pre><p>The Order model currently hosts callback methods, entangled with method logic defined within each function. Additionally, certain callbacks are detached from the core functionality of the Order object. This setup complicates testing and debugging, potentially making it challenging to identify and rectify issues.</p><p>To address these challenges and enhance maintainability, we can employ service objects and concerns. By extracting the logic from callbacks, we can create <strong>reusable</strong> code blocks applicable across multiple models. This restructuring ensures streamlined testing and debugging processes, fostering a more efficient and adaptable codebase.</p><p>Now, let’s refactor this example. Here’s how we’d do it:</p><h3>Creating Service Objects</h3><pre>class Mailer<br>    def self.send_confirmation_email(order)<br>      # Send confirmation email logic here...<br>    end<br>  end<br>  <br>  class Pdf<br>    def self.generate_invoice(order)<br>      # Generation of pdf logic goes here...<br>    end<br>  end</pre><h3>Creating Concerns and Using Service Objects</h3><pre>module Logable<br>    extend ActiveSupport::Concern<br>  <br>    included do<br>      after_commit :update_user_activity_log<br>    end<br>  <br>    private<br>  <br>    def update_user_activity_log<br>      # Update current_user log here...<br>    end<br>  end</pre><h3>Refactored version of the model</h3><pre>class Order &lt; ApplicationRecord<br>    belongs_to :user<br>  <br>    include Logable<br>  <br>    after_create :generate_invoice, :send_confirmation_email<br>  <br>    private<br>  <br>    def generate_invoice<br>      Pdf.generate_invoice(self)<br>    end<br>  <br>    def send_confirmation_email<br>      Mailer.send_confirmation_email(self)<br>    end<br>  end</pre><p>In the process of refactoring the Order model, we&#39;ve optimized the code by introducing service objects dedicated to distinct tasks, such as sending emails and generating PDFs. This strategic approach not only improves the model&#39;s testability, readability, and maintainability but also aligns with recommended Rails development practices.</p><p>The incorporation of concern Logable together with the Mailer and Pdf services have played key roles in organizing shared functionalities within the model. This deliberate structuring results in a more transparent and succinct model, fostering better modularity, streamlined testing processes, and an overall more sustainable codebase.</p><p>Please note that the examples provided are hypothetical and created for illustrative purposes, not based on actual implementations in a specific system or application. They serve as demonstrations to showcase best practices or potential solutions within a coding context.</p><p>Happy codding!</p><p><em>Originally published at </em><a href="https://egemen-dev.github.io/2024/01/06/refactoring-approach-on-rails-callbacks.html"><em>https://egemen-dev.github.io</em></a><em> on January 6, 2024.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=db33cb041591" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How to create a dynamic search bar with Hotwire?]]></title>
            <link>https://medium.com/@egemenn/how-to-create-a-dynamic-search-bar-with-hotwire-25fca98d9c79?source=rss-4c896e4e8235------2</link>
            <guid isPermaLink="false">https://medium.com/p/25fca98d9c79</guid>
            <category><![CDATA[javascript]]></category>
            <category><![CDATA[hotwire-rails]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[searchbar]]></category>
            <dc:creator><![CDATA[Egemen Öztürk]]></dc:creator>
            <pubDate>Sun, 03 Dec 2023 17:00:24 GMT</pubDate>
            <atom:updated>2024-07-15T09:15:32.234Z</atom:updated>
            <content:encoded><![CDATA[<p>Ever envisioned seamlessly incorporating a dynamic search bar into your web app, instantly triggered upon typing? Discover how to effortlessly implement this feature in your Rails 7 application using the powerful combination of Stimulus and TurboStream, a.k.a. Hotwire.</p><h3>Used gems:</h3><ul><li>faker - to generate fake books</li><li>requestjs-rails - to simplify the stimulus controller</li></ul><h3>Example behaviour:</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/463/0*u3g7KSeIGjqhUm0f.gif" /></figure><p>In this straightforward example, we’re using a Book model with just one attribute: its title. The goal is to perform searches based on these book titles.</p><h3>Routes</h3><pre>#routes.rb<br><br>Rails.application.routes.draw do<br>  root &quot;books#index&quot;<br><br>  resources :books do<br>    collection do<br>      get :search<br>    end<br>  end<br>end</pre><p>Basic routes.</p><h3>Migration</h3><pre>#create_books.rb<br><br>class CreateBooks &lt; ActiveRecord::Migration[7.1]<br>  def change<br>    create_table :books do |t|<br>      t.string :title<br><br>      t.timestamps<br>    end<br>  end<br>end</pre><p>Before creating any book we first need to create a simple migration.</p><h3>Seed</h3><pre>#seed.rb<br><br>100.times do<br>  Book.create(title: Faker::Book.title)<br>end</pre><p>Creation of the dummy books with faker gem.</p><p>For the sake of the example app here, I run the migrations and seed file. Finish setting up our basic app.</p><h3>Views</h3><p>Book partial.</p><pre>#_book.html.erb<br><br>&lt;div id=&quot;&lt;%= dom_id book %&gt;&quot;&gt;<br>  &lt;div&gt;<br>    &lt;%= link_to book.title, book %&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p>Index view file.</p><pre>#index.html.erb<br><br>&lt;h1&gt;Books&lt;/h1&gt;<br><br>&lt;input<br>  type=&quot;text&quot;<br>  placeholder=&quot;Search Books&quot;<br>  data-controller=&quot;search&quot;               &lt;-- Connecting stimulus controller &#39;search_controller.js&#39;<br>  data-action=&quot;input-&gt;search#search&quot;     &lt;-- This search() method will be called inside our stimulus controller in every keystroke <br>  data-search-target=&quot;searchBox&quot;         &lt;-- Sets the target name so we can get this spesifc DOM and read its input value inside the stimulus controller<br>  data-path=&quot;&lt;%= search_books_path %&gt;&quot;   &lt;-- Sets the path. We are going to use this path to send our search requests inside the stimulus controller<br>/&gt;<br><br>&lt;div id=&quot;books&quot;&gt;<br>  &lt;ol&gt;<br>    &lt;% @books.each do |book| %&gt;<br>    &lt;li&gt;<br>      &lt;%= render &quot;book&quot;, book: %&gt;<br>    &lt;/li&gt;<br>    &lt;% end %&gt;<br>  &lt;/ol&gt;<br>&lt;/div&gt;</pre><p>This turbo_stream view plays a crucial role in our functionality as it replaces the DOM with the id ‘books’ with the updated search results.</p><pre>#search.turbo_stream.erb<br><br>&lt;%= turbo_stream.replace &quot;books&quot; do %&gt;<br>  &lt;div id=&quot;books&quot;&gt;<br><br>    &lt;% if @books.empty? %&gt;<br>      &lt;h4&gt;No books were found!&lt;/h4&gt;<br>    &lt;% else %&gt;<br>      &lt;ol&gt;<br>        &lt;% @books.each do |book| %&gt;<br>          &lt;li&gt;<br>            &lt;%= render &#39;book&#39;, book: book %&gt;<br>          &lt;/li&gt;<br>        &lt;% end %&gt;<br>      &lt;/ol&gt;<br>    &lt;% end %&gt;<br><br>  &lt;/div&gt;<br>&lt;% end %&gt;</pre><h3>JS Controller</h3><pre>#index.html.erb<br><br>&lt;h1&gt;Books&lt;/h1&gt;<br><br>&lt;input<br>  type=&quot;text&quot;<br>  placeholder=&quot;Search Books&quot;<br>  data-controller=&quot;search&quot;               &lt;-- Connecting stimulus controller &#39;search_controller.js&#39;<br>  data-action=&quot;input-&gt;search#search&quot;     &lt;-- This search() method will be called inside our stimulus controller in every keystroke <br>  data-search-target=&quot;searchBox&quot;         &lt;-- Sets the target name so we can get this spesifc DOM and read its input value inside the stimulus controller<br>  data-path=&quot;&lt;%= search_books_path %&gt;&quot;   &lt;-- Sets the path. We are going to use this path to send our search requests inside the stimulus controller<br>/&gt;<br><br>&lt;div id=&quot;books&quot;&gt;<br>  &lt;ol&gt;<br>    &lt;% @books.each do |book| %&gt;<br>    &lt;li&gt;<br>      &lt;%= render &quot;book&quot;, book: %&gt;<br>    &lt;/li&gt;<br>    &lt;% end %&gt;<br>  &lt;/ol&gt;<br>&lt;/div&gt;</pre><p>This is the search_controller.js and it constructs the search query.</p><h3>Controllers</h3><pre>#books_controller.rb<br><br>class BooksController &lt; ApplicationController<br>  def index<br>    @books = Book.all<br>  end<br><br>  def search<br>    @books = if params[:query].present?<br>               Book.where(&#39;title LIKE ?&#39;, &quot;%#{params[:query]}%&quot;)<br>             else<br>               Book.all<br>             end<br>  end<br>end</pre><p>This is how the books_controller.rb looks like, it gets the job done. You can customize it as you wish. Maybe add limit to the seach query or add pagination :)</p><p>This is how you can integrate a fundamental search bar into your Ruby on Rails application using Hotwire.</p><p>Feel free to tailor this approach to your specific needs-consider introducing a delay in the Stimulus controller to prevent requests after each keystroke or implementing a limit in the books controller for added customization.</p><p><em>Originally published at </em><a href="https://egemen-dev.github.io/2023/12/03/dynamic-searchbar-hotwire.html"><em>https://egemen-dev.github.io</em></a><em> on December 3, 2023.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=25fca98d9c79" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>