<?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 Vaibhav Jain on Medium]]></title>
        <description><![CDATA[Stories by Vaibhav Jain on Medium]]></description>
        <link>https://medium.com/@vaibhavdjain?source=rss-8aca5e6f75d4------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*lQM7X1KhfJOgeWfA</url>
            <title>Stories by Vaibhav Jain on Medium</title>
            <link>https://medium.com/@vaibhavdjain?source=rss-8aca5e6f75d4------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Tue, 24 Nov 2026 09:11:15 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@vaibhavdjain/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[ Bundler (bundle install) – Complete Guide]]></title>
            <link>https://vaibhavdjain.medium.com/bundler-bundle-install-complete-guide-fc0403584502?source=rss-8aca5e6f75d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/fc0403584502</guid>
            <category><![CDATA[ruby-on-rails-development]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[performance]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[bundle]]></category>
            <dc:creator><![CDATA[Vaibhav Jain]]></dc:creator>
            <pubDate>Tue, 17 Mar 2026 07:54:23 GMT</pubDate>
            <atom:updated>2026-03-17T07:54:23.949Z</atom:updated>
            <content:encoded><![CDATA[<h3>Bundler is the dependency manager used in Ruby on Rails and Ruby projects.<br>It installs all required gems defined in your Gemfile.</h3><h3>🔹 1. Basic Usage</h3><pre>bundle install</pre><p>✔ Installs all gems listed in Gemfile<br>✔ Uses Gemfile.lock for exact versions<br>✔ Installs gems sequentially (default behavior)</p><h3>⚡ 2. Performance Optimization (IMPORTANT)</h3><h3>🔥 --jobs Option (Parallel Installation)</h3><pre>bundle install --jobs=4</pre><ul><li>Installs multiple gems <strong>in parallel</strong></li><li>Default (without jobs): installs <strong>one-by-one (slow)</strong></li></ul><h3>⭐ Best Version (Auto CPU Detection)</h3><pre>bundle install --jobs=$(nproc)</pre><h3>🔍 What is $(nproc)?</h3><ul><li>It is a Linux command that returns <strong>number of CPU cores</strong></li></ul><p>Example:</p><ul><li>2-core CPU → uses 2 jobs</li><li>8-core CPU → uses 8 jobs</li></ul><h3>🎯 Why Use --jobs=$(nproc)?</h3><h3>1. 🚀 Faster Installation</h3><ul><li>Gems download + compile in parallel</li><li>Huge speed improvement for large projects</li></ul><h3>2. 🧠 Efficient CPU Utilization</h3><ul><li>Uses full system capability</li><li>Avoids underutilizing hardware</li></ul><h3>3. 📦 Ideal for Large Projects</h3><ul><li>Rails apps with many gems benefit the most</li></ul><h3>⚠️ When to Use It</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/809/1*RLG2pEh6LJxzVBVQu8stxw.png" /></figure><h3>❌ When NOT to Use High Jobs</h3><p>Avoid very high values if:</p><ul><li>System has <strong>low RAM (≤ 2GB)</strong></li><li>Gems require heavy native compilation</li></ul><p>👉 In such cases:</p><pre>bundle install --jobs=2</pre><h3>🔁 3. Retry Option</h3><pre>bundle install --retry=3</pre><p>✔ Retries failed downloads<br>✔ Useful for unstable internet</p><h3>📦 4. Installation Path Options</h3><h3>--path</h3><pre>bundle install --path vendor/bundle</pre><p>✔ Installs gems inside project<br>✔ Avoids global gem pollution<br>✔ Used in deployment</p><h3>--deployment</h3><pre>bundle install --deployment</pre><p>✔ Production-safe mode<br>✔ Uses only Gemfile.lock<br>✔ Installs in vendor/bundle<br>✔ Prevents accidental changes</p><h3>🚫 5. Group Control</h3><h3>Skip groups</h3><pre>bundle install --without development test</pre><p>✔ Avoids installing unnecessary gems</p><h3>Include specific groups</h3><pre>bundle install --with production</pre><h3>🔒 6. Lockfile Safety</h3><h3>--frozen</h3><pre>bundle install --frozen</pre><p>✔ Prevents modifying Gemfile.lock<br>✔ Fails if mismatch detected</p><h3>🧹 7. Cleanup Options</h3><h3>--clean</h3><pre>bundle install --clean</pre><p>✔ Removes unused gems</p><h3>--no-cache</h3><pre>bundle install --no-cache</pre><p>✔ Does not store downloaded gems</p><h3>⚙️ 8. Persistent Configuration (Recommended)</h3><p>Instead of typing flags every time:</p><pre>bundle config set jobs $(nproc)<br>bundle config set retry 3<br>bundle config set path vendor/bundle</pre><p>Now just run:</p><pre>bundle install</pre><h3>🚀 9. Best Practice Commands</h3><h3>👨‍💻 Development</h3><pre>bundle install --jobs=$(nproc) --retry=3</pre><h3>🏭 Production</h3><pre>bundle install \<br>  --deployment \<br>  --without development test \<br>  --jobs=$(nproc) \<br>  --retry=3</pre><h3>🐳 Docker (Highly Recommended)</h3><pre>bundle install --jobs=$(nproc) --retry=3 --path vendor/bundle</pre><h3>🧠 Key Takeaways</h3><ul><li>bundle install by default is <strong>slow (sequential)</strong></li><li>--jobs=$(nproc) makes it <strong>parallel and fast</strong></li><li>Always combine with --retry=3 for stability</li><li>Use --deployment in production</li><li>Persist config using bundle config</li></ul><h3>💬 Simple Explanation</h3><p>👉 Without jobs:</p><blockquote><em>Install gems one by one → slow</em></blockquote><p>👉 With jobs:</p><blockquote><em>Install gems together → fast 🚀</em></blockquote><p>👉 With $(nproc):</p><blockquote><em>Automatically use full CPU power → smartest choice</em></blockquote><p>If you want, I can also show:</p><ul><li>🔥 <strong>Real benchmark (with vs without jobs)</strong></li><li>🐳 <strong>Optimized Dockerfile for Rails</strong></li><li>⚙️ <strong>CI/CD config (GitHub Actions / GitLab)</strong></li></ul><h3>📊 10. Real Benchmark: With vs Without --jobs=$(nproc)</h3><p>To understand the real impact, let’s compare installation times in a typical Ruby on Rails project.</p><h3>🧪 Test Setup</h3><ul><li>Project: Medium-size Rails app (~80–120 gems)</li></ul><p>Machine:</p><ul><li>CPU: 4 cores</li><li>RAM: 8 GB</li><li>OS: Linux</li><li>Network: Stable broadband</li></ul><h3>⏱️ Benchmark Results</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/940/1*KJn43htHVmcQtsoI7Wne3Q.png" /></figure><h3>📉 Performance Improvement</h3><ul><li>--jobs=4 → ~40% faster</li><li>--jobs=$(nproc) → ~50% faster</li></ul><p>👉 Larger projects (150+ gems):</p><ul><li>Can see <strong>60–70% improvement</strong></li></ul><h3>🔍 Why This Speed Gain Happens</h3><h3>Without --jobs</h3><ul><li>Gems install <strong>one-by-one</strong></li><li>CPU sits idle most of the time</li></ul><h3>With --jobs</h3><ul><li>Multiple gems:</li><li>Downloaded simultaneously</li><li>Compiled simultaneously</li><li>CPU fully utilized</li></ul><h3>📦 Real Scenario Breakdown</h3><h3>Example Gems That Benefit Most:</h3><ul><li>nokogiri (native compilation)</li><li>pg (PostgreSQL adapter)</li><li>ffi, rmagick</li></ul><p>👉 These take time individually — parallelism reduces total wait time.</p><h3>⚠️ Important Observations</h3><h3>1. Diminishing Returns</h3><ul><li>Increasing jobs beyond CPU cores → no major gain</li></ul><h3>2. Memory Usage Increases</h3><ul><li>Each job consumes RAM</li><li>On low-memory systems → system may slow down</li></ul><h3>🧠 Recommended Strategy</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/511/1*3XqA1XkRB4unS0cOWxZfkg.png" /></figure><h3>💡 Pro Insight (Very Useful)</h3><p>👉 If you run this often:</p><pre>bundle config set jobs $(nproc)</pre><p>You permanently get:</p><ul><li>Faster installs</li><li>No need to remember flags</li></ul><h3>🏁 Final Verdict</h3><ul><li>bundle install → ❌ Slow (sequential)</li><li>--jobs=4 → ✅ Faster</li><li>--jobs=$(nproc) → 🚀 Fastest &amp; smartest</li></ul><p>👉 <strong>Always prefer </strong><strong>--jobs=$(nproc) unless system constraints exist</strong></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fc0403584502" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Deep Dive: JWT Authentication for multiple microservices]]></title>
            <link>https://vaibhavdjain.medium.com/deep-dive-jwt-authentication-for-multiple-microservices-8fd9a0fbca2e?source=rss-8aca5e6f75d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/8fd9a0fbca2e</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[jwt-token]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[jwt]]></category>
            <dc:creator><![CDATA[Vaibhav Jain]]></dc:creator>
            <pubDate>Mon, 18 Aug 2025 12:41:37 GMT</pubDate>
            <atom:updated>2025-08-18T12:41:37.421Z</atom:updated>
            <content:encoded><![CDATA[<h3>Introduction</h3><p>Managing authentication and authorization across microservices can be tricky. When one service handles user login and token generation (like Service A), and others (B, C, D) need to authenticate requests, the question becomes:</p><blockquote><strong><em>How do you validate the token in each service without making Service A a bottleneck?</em></strong></blockquote><p>This article explores how <strong>JWT (JSON Web Tokens)</strong> solve this problem securely and efficiently. We’ll walk through internal mechanics, code examples, potential attack scenarios, and best practices.</p><h3>Scenario: Microservices Architecture</h3><ul><li><strong>A</strong>: Authentication Service (Login, Token generation)</li><li><strong>B</strong>: User Management Service</li><li><strong>C</strong>: Product Management Service</li><li><strong>D</strong>: Inventory Management Service</li></ul><p>Each service has:</p><ul><li>Its own database</li><li>Its own port</li><li>No shared tables</li></ul><blockquote><em>Goal: Authenticate users across B, C, and D using tokens issued by A, without making frequent calls to A.</em></blockquote><h3>✅ Why JWT?</h3><p>JWTs are <strong>self-contained tokens</strong> that include all necessary information about the user, and are <strong>signed</strong> to prevent tampering.</p><ul><li>No need to hit the database to validate every request.</li><li>Microservices can validate token signatures locally.</li><li>Token contains claims like user ID, email, role, and expiration.</li></ul><h3>🔐 Token Generation in Service A</h3><h3>Example: Ruby JWT Generation (HS256)</h3><pre>require &#39;jwt&#39;</pre><pre>payload = {<br>  sub: &quot;user_123&quot;,<br>  email: &quot;user@example.com&quot;,<br>  role: &quot;admin&quot;,<br>  exp: Time.now.to_i + 3600<br>}</pre><pre>secret = ENV[&#39;JWT_SECRET&#39;]</pre><pre>token = JWT.encode(payload, secret, &#39;HS256&#39;)<br>puts token</pre><p>This outputs a JWT like:</p><pre>eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJzdWIiOiJ1c2VyXzEyMyIsImVtYWlsIjoidXNlckBleGFtcGxlLmNvbSIsInJvbGUiOiJhZG1pbiIsImV4cCI6MTcwMDAwMDAwMH0.F2y9U2qGciCcWwtWVoKnO_PJrFfA0FZpKYUlUbOeuqk</pre><h3>🔍 JWT Structure Explained</h3><p>A JWT has 3 parts:</p><pre>&lt;base64url header&gt;.&lt;base64url payload&gt;.&lt;signature&gt;</pre><h3>Header:</h3><pre>{<br>  &quot;alg&quot;: &quot;HS256&quot;,<br>  &quot;typ&quot;: &quot;JWT&quot;<br>}</pre><h3>Payload:</h3><pre>{<br>  &quot;sub&quot;: &quot;user_123&quot;,<br>  &quot;email&quot;: &quot;user@example.com&quot;,<br>  &quot;role&quot;: &quot;admin&quot;,<br>  &quot;exp&quot;: 1700000000<br>}</pre><h3>Signature:</h3><pre>HMAC-SHA256(base64url(https://medium.com/header) + &quot;.&quot; + base64url(https://medium.com/payload), secret)</pre><h3>🔓 Token Verification in B, C, D</h3><h3>Ruby Code in a Controller</h3><pre>require &#39;jwt&#39;</pre><pre>SECRET = ENV[&#39;JWT_SECRET&#39;]<br><br>def authenticate_request<br>  token = request.headers[&#39;Authorization&#39;]&amp;.split(&#39; &#39;)&amp;.last<br>  begin<br>    decoded_token = JWT.decode(token, SECRET, true, { algorithm: &#39;HS256&#39; })<br>    @current_user_id = decoded_token[0][&#39;sub&#39;]<br>  rescue JWT::DecodeError =&gt; e<br>    render json: { error: &#39;Invalid token&#39; }, status: :unauthorized<br>  end<br>end</pre><h3>🔍 What happens internally?</h3><p>JWT tokens are signed like this (in simplified terms):</p><pre>signed_token = base64url(https://medium.com/header) + &#39;.&#39; + base64url(https://medium.com/payload) + &#39;.&#39; + HMAC-SHA256(secret, data)</pre><p>When you call:</p><pre>JWT.decode(token, SECRET_KEY, true, { algorithm: &#39;HS256&#39; })</pre><p>Here’s what happens internally:</p><ul><li>JWT library splits the token:</li></ul><pre>[header, payload, signature]</pre><ul><li>It recalculates the signature using your actual SECRET_KEY.</li><li>Then it compares it to the signature attached in the token.</li><li>If they match → Valid token.</li></ul><h3>🚨 Attacker Scenario: Can I Forge a Token?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/348/1*J9lWAwF9vALhOfaefrxnbQ.png" /></figure><blockquote><strong><em>What if someone creates a token with same payload and algorithm? Will it work?</em></strong></blockquote><h3>Example Attack:</h3><pre>{<br>  &quot;sub&quot;: &quot;hacker&quot;,<br>  &quot;email&quot;: &quot;badguy@evil.com&quot;,<br>  &quot;role&quot;: &quot;admin&quot;<br>}</pre><p>Then signs it with:</p><pre>JWT.encode(payload, &#39;123456&#39;, &#39;HS256&#39;)</pre><p>If your services use:</p><pre>JWT.decode(token, ENV[&#39;JWT_SECRET&#39;], true, { algorithm: &#39;HS256&#39; })</pre><p><strong>Result:</strong> If attacker <strong>doesn’t know your secret</strong>, the signature won’t match. JWT will raise:</p><pre>JWT::VerificationError: Signature verification raised</pre><p>✅ <strong>You’re safe</strong> if your JWT_SECRET is strong and private.</p><h3>🔐 Use RS256 for Better Security (Recommended)</h3><p>With RS256:</p><ul><li><strong>A</strong> uses private key to sign.</li><li><strong>B, C, D</strong> use public key to verify.</li><li>Even if B/C/D are compromised, attacker can’t forge token.</li></ul><h3>🔁 Token Revocation / Logout</h3><p>JWTs are stateless. Once issued, they can’t be invalidated unless:</p><ul><li>You keep a <strong>revoked token blacklist</strong>.</li><li>Use <strong>short expiration + refresh tokens</strong>.</li><li>Add a jti (JWT ID) claim and store it in Redis for active sessions.</li></ul><h3>✅ Summary Checklist</h3><ul><li>Use long random secrets ✅</li><li>Never decode without verification ✅</li><li>Use exp (expiration) claims ✅</li><li>Consider RS256 for better isolation ✅</li><li>Rotate secrets if compromised ✅</li></ul><h3>🧪 Testing JWT Security</h3><p>Use tools like:</p><ul><li><a href="https://jwt.io/">https://jwt.io</a></li><li>Burp Suite / Postman</li><li>Custom scripts to forge payloads and test invalid signatures</li></ul><h3>📌 Final Thoughts</h3><p>JWT is a powerful tool when used correctly. For microservices, it removes the need for centralized auth validation on every request, while still being secure — <strong>as long as you verify signatures and keep your secrets safe.</strong></p><p>For high-security environments, use <strong>RS256</strong> or even a <strong>Gateway with token introspection</strong>.</p><p><strong>Tags</strong>: #JWT #Security #Microservices #RubyOnRails #Auth #API</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*7NTeqmtpUH2A94S3J1CCiw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8fd9a0fbca2e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Understanding includes, preload, and eager_load in Rails]]></title>
            <link>https://vaibhavdjain.medium.com/understanding-includes-preload-and-eager-load-in-rails-fa1cdfa79043?source=rss-8aca5e6f75d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/fa1cdfa79043</guid>
            <category><![CDATA[optimization]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby-on-rails-development]]></category>
            <category><![CDATA[technology]]></category>
            <dc:creator><![CDATA[Vaibhav Jain]]></dc:creator>
            <pubDate>Thu, 14 Aug 2025 09:47:58 GMT</pubDate>
            <atom:updated>2025-08-14T09:47:58.103Z</atom:updated>
            <content:encoded><![CDATA[<p>If you’ve worked with Rails for a while, you’ve probably run into the <strong>N+1 query problem</strong>. It’s one of those sneaky performance killers that starts small but can wreck your app’s response times as data grows.</p><p>Rails gives us three main tools to solve it: <strong>includes</strong>, <strong>preload</strong>, and <strong>eager_load</strong>.<br> They sound similar, but they work differently — and knowing when to use which one can save you a ton of pain.</p><h3>The Problem: N+1 Queries</h3><p>Imagine we have two models:</p><pre>class User &lt; ApplicationRecord<br>  has_many :posts<br>end</pre><pre>class Post &lt; ApplicationRecord<br>  belongs_to :user<br>end</pre><p>And we want to print how many posts each user has:</p><pre>users = User.all<br>users.each do |user|<br>  puts &quot;#{user.name} - #{user.posts.count} posts&quot;<br>end</pre><p>Without optimization, Rails will:</p><ol><li>Load all users in <strong>one query</strong>.</li><li>Then, for each user, run another query for their posts.</li></ol><p>If you have 100 users:</p><ul><li>1 query for users</li><li>100 queries for posts<br> That’s <strong>101 queries</strong>. Ouch.</li></ul><h3>The Solution: Preloading / Eager Loading</h3><h3>1️⃣ preload</h3><ul><li>Runs <strong>separate queries</strong> for associations.</li><li>One query for the main table, and another for each association (but <strong>only once</strong>).</li><li>Rails stitches the results together in memory.</li></ul><p>Example:</p><pre>users = User.preload(:posts)</pre><p>SQL:</p><pre>SELECT * FROM users;<br>SELECT * FROM posts WHERE user_id IN (1, 2, 3, ...);</pre><p><strong>When to use:</strong></p><ul><li>You <strong>don’t</strong> need to filter or sort by associated data in SQL.</li><li>Keeps queries simpler, avoids heavy joins.</li></ul><h3>2️⃣ eager_load</h3><ul><li>Loads everything in <strong>one query</strong> using a <strong>LEFT OUTER JOIN</strong>.</li><li>Necessary if you filter or sort by associated data in SQL.</li></ul><p>Example:</p><pre>users = User.eager_load(:posts).where(posts: { published: true })</pre><p>SQL:</p><pre>SELECT users.*, posts.* <br>FROM users<br>LEFT OUTER JOIN posts ON posts.user_id = users.id<br>WHERE posts.published = true;</pre><p><strong>When to use:</strong></p><ul><li>You need to filter (WHERE) or sort (ORDER BY) based on associated data.</li><li>Be careful: joins can produce <strong>duplicate parent rows</strong> if there are multiple associated records.</li></ul><h3>3️⃣ includes</h3><ul><li>The “smart” option.</li><li>Rails decides between preload and eager_load based on how you use the association in the query.</li></ul><p>Example:</p><pre>users = User.includes(:posts)</pre><p>If you don’t filter on posts:</p><pre>SELECT * FROM users;<br>SELECT * FROM posts WHERE user_id IN (...);</pre><p>If you do:</p><pre>users = User.includes(:posts).where(posts: { published: true })</pre><p>Rails automatically switches to a join:</p><pre>SELECT users.*, posts.* <br>FROM users<br>LEFT OUTER JOIN posts ON posts.user_id = users.id<br>WHERE posts.published = true;</pre><p><strong>When to use:</strong></p><ul><li>Most of the time.</li><li>Lets Rails decide the strategy.</li></ul><h3>TL;DR Table</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*cG7pVUgM6MQfvtBT--ibJQ.png" /></figure><p><strong>Final Tip:</strong><br>If you’re unsure, start with includes. If you notice duplicate rows or complex joins slowing things down, switch to preload. If you need to filter/sort on the joined table, use eager_load.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*7NTeqmtpUH2A94S3J1CCiw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=fa1cdfa79043" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Building Real-Time Partial Component Updates in Rails 8.0.2 with Turbo Frames (Ruby 3.4.5)]]></title>
            <link>https://vaibhavdjain.medium.com/building-real-time-partial-component-updates-in-rails-8-0-2-with-turbo-frames-ruby-3-4-5-f11c94fa7e4f?source=rss-8aca5e6f75d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/f11c94fa7e4f</guid>
            <category><![CDATA[stimulus]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[turbo]]></category>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Vaibhav Jain]]></dc:creator>
            <pubDate>Sun, 10 Aug 2025 17:10:59 GMT</pubDate>
            <atom:updated>2025-08-10T17:49:12.022Z</atom:updated>
            <content:encoded><![CDATA[<p><em>A complete guide to creating modern Rails applications with partial page updates, sidebar editing, and persistent component timers using Hotwire Turbo</em></p><h3>The Problem: Creating Smooth User Experiences in Rails</h3><p>Traditional Rails applications often suffer from the jarring experience of full page reloads when users interact with content. Users click “Edit,” the entire page refreshes, they make changes, submit, and face another full page reload. This creates a disjointed experience that feels outdated in today’s web landscape.</p><p>What if we could create a Rails application where:</p><ul><li>Users see a list of components with <strong>real-time running timers</strong></li><li>Clicking “Edit” opens a <strong>form in a sidebar</strong> without page refresh</li><li>Submitting updates <strong>only refreshes the specific component</strong></li><li>The form <strong>automatically closes</strong> after successful updates</li><li>Timers <strong>continue running</strong> and restart appropriately after updates</li></ul><p>This is exactly what we’ll build using Rails and Hotwire Turbo.</p><h3>Project Overview</h3><p>We’ll create a component management system with these features:</p><ul><li><strong>Two-column layout</strong>: Components list on the left, edit form on the right</li><li><strong>Partial updates</strong>: Only the edited component refreshes</li><li><strong>Real-time timers</strong>: Each component shows how long it’s been active</li><li><strong>Seamless editing</strong>: Edit forms appear in sidebar and auto-close</li></ul><h3>Step 1: Setting Up the Rails Project</h3><p>Create a new Rails project with Hotwire:</p><pre>rails new dynamic_components_app<br>cd dynamic_components_app</pre><p>Add the necessary gems to your Gemfile:</p><pre>gem &#39;turbo-rails&#39;<br>gem &#39;stimulus-rails&#39;</pre><p>Install and configure Hotwire:</p><pre>bundle install<br>rails turbo:install stimulus:install</pre><h3>Step 2: Creating the Component Model</h3><p>Generate a scaffold for our components:</p><pre>rails generate scaffold Component name:string content:text<br>rails db:migrate</pre><p>Add validations to app/models/component.rb: (optional)</p><pre>class Component &lt; ApplicationRecord<br>  validates :name, presence: true<br>  validates :content, presence: true<br>end</pre><p>Set up your routes in config/routes.rb:</p><pre>Rails.application.routes.draw do<br>  root &quot;components#index&quot;<br>  resources :components<br>end</pre><h3>Step 3: Building the Two-Column Interface</h3><p>The magic starts with our layout. Update app/views/components/index.html.erb:</p><pre>&lt;h1&gt;Components&lt;/h1&gt;<br><br>&lt;div style=&quot;display: flex; gap: 20px;&quot;&gt;<br>  &lt;!-- Left side: Components list --&gt;<br>  &lt;div style=&quot;flex: 1; border-right: 1px solid #ccc; padding-right: 20px;&quot;&gt;<br>    &lt;div id=&quot;components-list&quot;&gt;<br>      &lt;%= render @components %&gt;<br>    &lt;/div&gt;<br>    &lt;%= link_to &quot;New Component&quot;, new_component_path %&gt;<br>  &lt;/div&gt;<br><br>  &lt;!-- Right side: Edit form placeholder --&gt;<br>  &lt;div style=&quot;flex: 1; padding-left: 20px;&quot;&gt;<br>    &lt;h2&gt;Edit Component&lt;/h2&gt;<br>    &lt;turbo-frame id=&quot;component_edit_frame&quot;&gt;<br>      &lt;p&gt;Select a component to edit&lt;/p&gt;<br>    &lt;/turbo-frame&gt;<br>  &lt;/div&gt;<br>&lt;/div&gt;</pre><p>This creates our foundation: a split view where the left side shows components and the right side will dynamically load edit forms.</p><h3>Step 4: Creating Component Partials with Timers</h3><p>Create app/views/components/_component.html.erb:</p><pre>&lt;div id=&quot;&lt;%= dom_id(component) %&gt;&quot; class=&quot;component&quot; <br>     style=&quot;border:1px solid #ccc; margin-bottom:10px; padding:10px;&quot;&gt;<br>  &lt;h3&gt;&lt;%= component.name %&gt;&lt;/h3&gt;<br>  &lt;p&gt;&lt;%= component.content %&gt;&lt;/p&gt;<br>  <br>  &lt;!-- Running timer display --&gt;<br>  &lt;p&gt;&lt;strong&gt;Running time: &lt;span id=&quot;timer-&lt;%= component.id %&gt;&quot;&gt;0&lt;/span&gt; seconds&lt;/strong&gt;&lt;/p&gt;<br>  <br>  &lt;!-- Edit link targets the right sidebar frame --&gt;<br>  &lt;%= link_to &quot;Edit&quot;, edit_component_path(component), <br>      data: { turbo_frame: &quot;component_edit_frame&quot; } %&gt;<br>&lt;/div&gt;</pre><p>Notice two key elements:</p><ol><li><strong>Timer span</strong> with unique ID: timer-&lt;%= component.id %&gt;</li><li><strong>Edit link</strong> with turbo_frame targeting our sidebar frame</li></ol><h3>Step 5: Setting Up the Edit Form</h3><p>The edit form must be wrapped in the correct Turbo Frame. Update app/views/components/edit.html.erb:</p><pre>&lt;turbo-frame id=&quot;component_edit_frame&quot;&gt;<br>  &lt;h3&gt;Editing: &lt;%= @component.name %&gt;&lt;/h3&gt;<br>  <br>  &lt;%= form_with(model: @component, local: false) do |form| %&gt;<br>    &lt;div class=&quot;field&quot;&gt;<br>      &lt;%= form.label :name %&gt;<br>      &lt;%= form.text_field :name %&gt;<br>    &lt;/div&gt;<br>    <br>    &lt;div class=&quot;field&quot;&gt;<br>      &lt;%= form.label :content %&gt;<br>      &lt;%= form.text_area :content, rows: 4 %&gt;<br>    &lt;/div&gt;<br>    <br>    &lt;div class=&quot;actions&quot;&gt;<br>      &lt;%= form.submit &quot;Update Component&quot; %&gt;<br>      &lt;%= link_to &quot;Cancel&quot;, components_path, <br>          data: { turbo_frame: &quot;component_edit_frame&quot; } %&gt;<br>    &lt;/div&gt;<br>  &lt;% end %&gt;<br>&lt;/turbo-frame&gt;</pre><p><strong>Critical Detail</strong>: The turbo-frame wrapper with id component_edit_frame is essential. Without it, you&#39;ll get this error:</p><pre>The response (200) did not contain the expected &lt;turbo-frame id=&quot;component_edit_frame&quot;&gt;</pre><h3>Step 6: Handling Updates with Turbo Streams</h3><p>The controller needs to handle both component updates and form closure. Update your update action in app/controllers/components_controller.rb:</p><pre>class ComponentsController &lt; ApplicationController<br>  before_action :set_component, only: [:show, :edit, :update, :destroy]<br><br>  def index<br>    @components = Component.all<br>  end<br><br>  def show<br>  end<br><br>  def new<br>    @component = Component.new<br>  end<br><br>  def edit<br>  end<br><br>  def create<br>    @component = Component.new(component_params)<br>    if @component.save<br>      redirect_to components_path, notice: &quot;Component created successfully.&quot;<br>    else<br>      render :new, status: :unprocessable_entity<br>    end<br>  end<br><br>  def update<br>    respond_to do |format|<br>      if @component.update(component_params)<br>        format.html { redirect_to components_path, notice: &quot;Component updated.&quot; }<br>        format.turbo_stream {<br>          render turbo_stream: [<br>            # Update the component in the left list<br>            turbo_stream.replace(@component, <br>              partial: &quot;components/component&quot;, <br>              locals: { component: @component }<br>            ),<br>            # Clear the edit form on the right<br>            turbo_stream.replace(&quot;component_edit_frame&quot;, <br>              &quot;&lt;p&gt;Component updated successfully! Select another to edit.&lt;/p&gt;&quot;<br>            )<br>          ]<br>        }<br>      else<br>        format.html { render :edit, status: :unprocessable_entity }<br>        format.turbo_stream {<br>          render turbo_stream: turbo_stream.replace(&quot;component_edit_frame&quot;, <br>            partial: &quot;components/edit&quot;, locals: { component: @component }<br>          )<br>        }<br>      end<br>    end<br>  end<br><br>  def destroy<br>    @component.destroy<br>    redirect_to components_path, notice: &quot;Component deleted.&quot;<br>  end<br><br>  private<br><br>  def set_component<br>    @component = Component.find(params[:id])<br>  end<br><br>  def component_params<br>    params.require(:component).permit(:name, :content)<br>  end<br>end</pre><p>The magic happens in the format.turbo_stream response which performs <strong>two simultaneous actions</strong>:</p><ol><li>Replaces the updated component in the list</li><li>Clears the edit form from the sidebar</li></ol><h3>Step 7: Implementing Real-Time Timers</h3><p>Here’s where we add the timer functionality. Add this JavaScript to your app/views/layouts/application.html.erb before the closing &lt;/body&gt; tag:</p><pre>&lt;script&gt;<br>  // Store all timer intervals globally<br>  window.componentTimers = [];<br><br>  function startTimers() {<br>    // Clear existing timers to prevent duplicates<br>    window.componentTimers.forEach(clearInterval);<br>    window.componentTimers = [];<br><br>    // Start timer for each component currently in DOM<br>    document.querySelectorAll(&quot;[id^=&#39;timer-&#39;]&quot;).forEach(timerSpan =&gt; {<br>      let count = 0;<br>      const interval = setInterval(() =&gt; {<br>        count++;<br>        timerSpan.textContent = count;<br>      }, 1000);<br>      window.componentTimers.push(interval);<br>    });<br>  }<br><br>  // Start timers on initial page load<br>  document.addEventListener(&quot;turbo:load&quot;, () =&gt; {<br>    startTimers();<br>  });<br><br>  // Restart timers when Turbo updates frames or content<br>  document.addEventListener(&quot;turbo:frame-load&quot;, () =&gt; {<br>    startTimers();<br>  });<br>&lt;/script&gt;</pre><h3>The Key Insight: Event-Driven Timer Management</h3><p>The crucial breakthrough came when we realized that <strong>Turbo frame updates don’t automatically trigger timer restarts</strong>. The solution is listening to both:</p><ul><li>turbo:load - Fires on initial page load</li><li>turbo:frame-load - Fires whenever Turbo updates any frame content</li></ul><p>This ensures timers restart after component updates, maintaining the real-time experience users expect.</p><h3>Testing Your Implementation</h3><p>To verify everything works correctly:</p><h3>1. Check Partial Updates</h3><p>Open browser DevTools → Network tab:</p><ul><li>Click “Edit” → Should see XHR request, not full page load</li><li>Submit form → Should see Turbo Stream response</li><li>No page flash or URL change</li></ul><h3>2. Verify Timer Behavior</h3><ul><li>Initial load: All timers start counting from 0</li><li>Edit a component: Form appears in sidebar, timers keep running</li><li>Submit update: Component updates, timers restart from 0</li><li>Cancel edit: Form disappears, timers continue</li></ul><h3>3. Network Inspection</h3><p>Look for these response types:</p><ul><li>Edit click: text/html response with turbo-frame content</li><li>Form submit: text/vnd.turbo-stream.html response</li></ul><h3>Common Pitfalls and Solutions</h3><h3>Issue: “Content missing” Error</h3><p><strong>Cause</strong>: Model validation failing or form parameters not submitted correctly.</p><p><strong>Solution</strong>: Check your component_params method and ensure form fields match model attributes:</p><pre>def component_params<br>  params.require(:component).permit(:name, :content)<br>end</pre><h3>Issue: Turbo Frame Not Found Error</h3><p><strong>Cause</strong>: Edit view not wrapped in correct turbo-frame.</p><p><strong>Solution</strong>: Always wrap edit forms in the target frame:</p><pre>&lt;turbo-frame id=&quot;component_edit_frame&quot;&gt;<br>  &lt;!-- form content --&gt;<br>&lt;/turbo-frame&gt;</pre><h3>Issue: Timers Stop After Updates</h3><p><strong>Cause</strong>: Only listening to turbo:load event.</p><p><strong>Solution</strong>: Also listen to turbo:frame-load for partial updates.</p><h3>Why This Approach Works</h3><p>This solution leverages several key Rails and Hotwire principles:</p><ol><li><strong>Server-Side Rendering</strong>: We maintain Rails’ strength in server-side HTML generation</li><li><strong>Progressive Enhancement</strong>: The app works without JavaScript, but enhances with it</li><li><strong>Minimal JavaScript</strong>: We use vanilla JS for timers, avoiding complex framework overhead</li><li><strong>Turbo Frames</strong>: Enable targeted page updates without custom AJAX code</li><li><strong>Turbo Streams</strong>: Allow multiple simultaneous page updates from a single request</li></ol><h3>Performance Considerations</h3><h3>Memory Management</h3><ul><li>Clear intervals when components are removed</li><li>Consider pausing timers for off-screen components using IntersectionObserver</li></ul><h3>Network Efficiency</h3><ul><li>Turbo Streams send minimal HTML payloads</li><li>No unnecessary full page renders</li></ul><h3>Scalability</h3><ul><li>For 100+ components, consider server-sent events for timer synchronization</li><li>Implement pagination for large component lists</li></ul><h3>Real-World Applications</h3><p>This pattern is perfect for:</p><ul><li><strong>Admin dashboards</strong> with inline editing capabilities</li><li><strong>Content management systems</strong> requiring frequent updates</li><li><strong>Monitoring applications</strong> with real-time data</li><li><strong>Project management tools</strong> with live status updates</li><li><strong>E-commerce backends</strong> with inventory management</li></ul><h3>Conclusion</h3><p>We’ve built a sophisticated Rails application that feels like a modern single-page application while maintaining all the benefits of server-side rendering. The combination of Hotwire Turbo’s Frames and Streams creates seamless user experiences without the complexity of a full JavaScript framework.</p><p>The real-time timer functionality demonstrates how to maintain client-side state that persists through Turbo updates, solving a common challenge when building interactive Rails applications.</p><p><strong>Key Takeaways:</strong></p><ul><li>Turbo Frames enable targeted page sections updates</li><li>Turbo Streams allow multiple simultaneous page changes</li><li>Event-driven JavaScript integrates smoothly with Turbo</li><li>Server-side rendering remains the foundation for reliable, accessible applications</li></ul><p>This approach gives you the interactivity users expect while keeping your Rails application maintainable and following established conventions.</p><h3>Complete File Structure</h3><p>For reference, here’s what your final project structure should include:</p><pre>app/<br>├── controllers/<br>│   └── components_controller.rb<br>├── models/<br>│   └── component.rb<br>├── views/<br>│   ├── layouts/<br>│   │   └── application.html.erb (with timer script)<br>│   └── components/<br>│       ├── index.html.erb<br>│       ├── edit.html.erb<br>│       └── _component.html.erb<br>config/<br>└── routes.rb<br>db/<br>└── migrate/<br>    └── create_components.rb</pre><p>Try implementing this in your next Rails project and experience the smooth, modern interactions your users will love!</p><p><strong>LinkedIn :-</strong> <a href="https://www.linkedin.com/in/vaibhav-jain-6454971a4">https://www.linkedin.com/in/vaibhav-jain-6454971a4</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*7NTeqmtpUH2A94S3J1CCiw.png" /></figure><p><strong>Tags:</strong> #Rails #Hotwire #Turbo #RealTime #JavaScript #WebDevelopment #RubyOnRails #PartialUpdates #ModernWeb #Tutorial</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=f11c94fa7e4f" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[ Securing APIs: OAuth2, JWT, and API Keys]]></title>
            <link>https://vaibhavdjain.medium.com/securing-apis-oauth2-jwt-and-api-keys-457c1466be44?source=rss-8aca5e6f75d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/457c1466be44</guid>
            <category><![CDATA[api]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[security]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[application]]></category>
            <dc:creator><![CDATA[Vaibhav Jain]]></dc:creator>
            <pubDate>Mon, 09 Jun 2025 11:52:07 GMT</pubDate>
            <atom:updated>2025-06-09T11:52:07.593Z</atom:updated>
            <content:encoded><![CDATA[<p>Here’s a <strong>detailed documentation draft</strong> for the topic: <strong>“Securing APIs: OAuth2, JWT, and API Keys”</strong>, including <strong>real-time examples</strong>, <strong>why you’d use each method</strong>, and <strong>when it’s helpful</strong>. You can publish this on Medium, use it in your internal docs, or adapt it for a knowledge base.</p><h3>📌 Why API Security Matters</h3><p>Without proper security:</p><ul><li>APIs become a primary attack surface.</li><li>Sensitive data can be leaked.</li><li>Abuse can go undetected or unblocked.</li></ul><p>So let’s dive into the tools available to you:</p><h3>🔑 1. API Keys</h3><h3>✅ What Are API Keys?</h3><p>API Keys are simple tokens used to identify and authenticate the client accessing your API. Usually sent via a header or query string.</p><pre>GET /api/v1/posts<br>X-API-Key: abc123xyz</pre><h3>🎯 When to Use</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*p0dK7fq1JscYOmN9BXOvgw.png" /></figure><h3>🚫 When Not to Use</h3><ul><li>When user-specific access or identity is needed.</li><li>If you require token expiration, scopes, or granular revocation.</li></ul><h3>⚙️ Real-Time Example</h3><p><strong>Scenario:</strong> You expose a GET /weather API and want to restrict it to paying clients.</p><p><strong>Implementation (Rails):</strong></p><pre>before_action :authenticate_api_key!</pre><pre>def authenticate_api_key!<br>  key = request.headers[&#39;X-API-Key&#39;]<br>  head :unauthorized unless ApiClient.find_by(api_key: key)<br>end</pre><h3>🛂 2. OAuth2</h3><h3>✅ What Is OAuth2?</h3><p>OAuth2 is an <strong>authorization framework</strong> that lets clients access user data <strong>without sharing their credentials</strong>. It issues access tokens on behalf of the user.</p><h3>🔁 Typical Flow</h3><ol><li>App redirects user to the auth provider (Google, Facebook, your own Doorkeeper server).</li><li>User approves.</li><li>App receives an access token.</li><li>App uses the token to call your API:</li></ol><pre>Authorization: Bearer eyJhbGciOi...</pre><h3>🎯 When to Use</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/971/1*TJjJkBleRLgdC5FIFMlRtw.png" /></figure><h3>🚫 When Not to Use</h3><ul><li>For internal-only APIs (unless centralized auth is needed).</li><li>For simple machine-to-machine communication (overkill).</li></ul><h3>⚙️ Real-Time Example</h3><p><strong>Scenario:</strong> A user wants to sync their Gmail contacts with your CRM.</p><p>You use <strong>Google OAuth2</strong> to:</p><ul><li>Redirect the user to Google for consent.</li><li>Receive a token back.</li><li>Use it to fetch contacts.</li></ul><p><strong>Popular Rails Gem:</strong></p><ul><li><a href="https://github.com/doorkeeper-gem/doorkeeper">doorkeeper</a></li></ul><h3>🪙 3. JWT (JSON Web Tokens)</h3><h3>✅ What Is JWT?</h3><p>JWT is a <strong>self-contained token format</strong> that carries claims (like user_id, role) and is cryptographically signed. It is commonly used as a bearer token in stateless APIs.</p><pre>Authorization: Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9...</pre><h3>🧠 Structure:</h3><pre>header.payload.signature</pre><p>Decoded payload:</p><pre>{<br>  &quot;sub&quot;: &quot;user_123&quot;,<br>  &quot;role&quot;: &quot;admin&quot;,<br>  &quot;exp&quot;: 1710000000<br>}</pre><h3>🎯 When to Use</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/867/1*ANYsDGYgHmoJ12Yj5_lDaA.png" /></figure><h3>🚫 When Not to Use</h3><ul><li>When you need easy token revocation (JWT is hard to blacklist).</li><li>If payload contains too much data.</li></ul><h3>⚙️ Real-Time Example</h3><p><strong>Scenario:</strong> A React app logs in the user with /auth/login, receives a JWT, and stores it in localStorage.</p><p>Then it makes a call:</p><pre>GET /profile<br>Authorization: Bearer &lt;JWT&gt;</pre><p><strong>Rails Code (Using </strong><strong>jwt gem):</strong></p><pre>payload = JWT.decode(token, Rails.application.secret_key_base)[0]<br>@current_user = User.find(payload[&quot;sub&quot;])</pre><h3>🧠 Decision Guide: Which to Choose?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DTv7-I_gkNWFAG8hWYvJ0g.png" /></figure><h3>🔐 Best Practices for All Methods</h3><ul><li>✅ Always use HTTPS to transmit credentials or tokens.</li><li>✅ Rotate and expire tokens or keys.</li><li>✅ Limit scope and permissions wherever possible.</li><li>✅ Log usage and anomalies.</li></ul><h3>📦 Summary</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*tpsCja0T8P9nelyLw6rvXw.png" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=457c1466be44" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Multi-Tenant Architecture]]></title>
            <link>https://vaibhavdjain.medium.com/multi-tenant-architecture-b16b063b75d5?source=rss-8aca5e6f75d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b16b063b75d5</guid>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[database]]></category>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[project-management]]></category>
            <category><![CDATA[architecture]]></category>
            <dc:creator><![CDATA[Vaibhav Jain]]></dc:creator>
            <pubDate>Mon, 09 Jun 2025 11:35:35 GMT</pubDate>
            <atom:updated>2025-06-09T11:35:35.782Z</atom:updated>
            <content:encoded><![CDATA[<p>Great question! Here’s a clear explanation of <strong>multi-tenant architecture</strong>:</p><h3>What is Multi-Tenant Architecture?</h3><p><strong>Multi-tenant architecture</strong> is a software design approach where a single instance of an application serves <strong>multiple separate customers or tenants</strong>. Each tenant shares the same application but their data and configurations remain isolated and secure from other tenants.</p><h3>Key Concepts</h3><ul><li><strong>Tenant:</strong> An individual customer, organization, or user group using the application.</li><li><strong>Isolation:</strong> Tenants have isolated data and sometimes configurations, ensuring privacy and security.</li><li><strong>Shared resources:</strong> The application, infrastructure, and often the database are shared to optimize cost and efficiency.</li></ul><h3>Why use Multi-Tenancy?</h3><ul><li><strong>Cost efficiency:</strong> One app instance serving many tenants reduces infrastructure and maintenance cost.</li><li><strong>Easier maintenance:</strong> One codebase and deployment to update for all tenants.</li><li><strong>Scalability:</strong> Can serve a large number of tenants without provisioning separate apps for each.</li><li><strong>Customization:</strong> Some systems allow tenant-specific features or configurations.</li></ul><h3>You can implement <strong>multi-tenant architecture</strong> in several ways depending on your isolation needs, scalability, and complexity. The common types are:</h3><h3>✅ 1. Shared Database, Shared Schema (Row-Level Isolation)</h3><ul><li><strong>Tenants share the same database and tables.</strong></li><li>Tenant data is separated by a tenant_id column in each table.</li><li>You filter queries using the tenant ID (e.g., using default_scope, ActsAsTenant, or Apartment gem in schema-less mode).</li></ul><p><strong>Pros:</strong></p><ul><li>Easy to implement.</li><li>Low cost, minimal infrastructure.</li><li>Fast tenant switching.</li></ul><p><strong>Cons:</strong></p><ul><li>Weaker isolation; bugs can leak data across tenants.</li><li>Harder to scale with many tenants or large data.</li></ul><h3>✅ 2. Shared Database, Separate Schemas</h3><ul><li><strong>All tenants share one database</strong>, but each tenant has <strong>its own schema</strong> (PostgreSQL).</li><li>You switch schemas per tenant request (e.g., Apartment gem or custom switching logic).</li></ul><p><strong>Pros:</strong></p><ul><li>Good data isolation.</li><li>Easier to manage migrations for a tenant.</li><li>Still cost-effective (only one DB server).</li></ul><p><strong>Cons:</strong></p><ul><li>Schema management can become complex with many tenants.</li><li>Rails doesn’t natively support multiple schemas as smoothly as single schema.</li></ul><h3>✅ 3. Separate Databases per Tenant</h3><ul><li>Each tenant gets a <strong>completely separate database</strong>.</li><li>Rails connects to the right database dynamically based on the current tenant (via middleware or context switch).</li></ul><p><strong>Pros:</strong></p><ul><li>Strongest isolation (security, performance).</li><li>Easy to scale or migrate individual tenants.</li></ul><p><strong>Cons:</strong></p><ul><li>Higher operational complexity.</li><li>More expensive.</li><li>Migrations need to be applied to each DB individually.</li></ul><h3>✅ 4. Hybrid Approaches</h3><ul><li><strong>Combination of above</strong>, for example:</li><li>VIP customers get separate databases.</li><li>Small customers use shared schema.</li></ul><h3>Choosing the Right Architecture</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/1*YGKlRsC0r_87fwuZ4w97mw.png" /></figure><p>Some popular <strong>Rails</strong> <strong>gems</strong> aligned with each <strong>multi-tenant architecture type</strong>:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*kebsgWeBcs4IeUDa-PhdQg.png" /></figure><h3>Other helpful gems/tools for multi-tenancy in Rails:</h3><ul><li><a href="https://github.com/ActsAsParanoid/acts_as_paranoid"><strong>ActsAsParanoid</strong></a></li></ul><p>Soft delete support, useful in multi-tenant apps for tenant-specific data retention.</p><ul><li><a href="https://github.com/RolifyCommunity/rolify"><strong>rolify</strong></a><strong> + </strong><a href="https://github.com/varvet/pundit"><strong>pundit</strong></a></li></ul><p>Role management and authorization, often necessary with tenancy for permission control.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b16b063b75d5" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Code Review Culture: How to Do It Right]]></title>
            <link>https://vaibhavdjain.medium.com/code-review-culture-how-to-do-it-right-b1129bf9bdad?source=rss-8aca5e6f75d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b1129bf9bdad</guid>
            <category><![CDATA[bitbucket]]></category>
            <category><![CDATA[review]]></category>
            <category><![CDATA[github]]></category>
            <category><![CDATA[programming]]></category>
            <category><![CDATA[gitlab]]></category>
            <dc:creator><![CDATA[Vaibhav Jain]]></dc:creator>
            <pubDate>Wed, 28 May 2025 12:20:34 GMT</pubDate>
            <atom:updated>2025-05-28T12:21:58.969Z</atom:updated>
            <content:encoded><![CDATA[<p>Code reviews are more than just a gatekeeping step before merging to main — they’re opportunities to <strong>improve code quality, share knowledge, and foster team collaboration</strong>. But a poor code review culture can lead to frustration, delays, or even toxic communication.</p><p>So how do you create a <strong>healthy, effective, and respectful code review culture</strong>?</p><p>Let’s break it down.</p><h3>🔍 What is Code Review?</h3><p>A code review is a systematic check of another developer’s code — usually in the form of pull requests (PRs) — to ensure it’s correct, clean, and consistent with the project’s standards.</p><p>But great code review culture is <strong>not just about finding bugs</strong>. It’s about:</p><ul><li>Mentorship and knowledge sharing</li><li>Enforcing coding standards</li><li>Catching potential issues early</li><li>Improving system design</li><li>Building team trust</li></ul><h3>🚩 The Red Flags of Poor Code Review Culture</h3><p>Before diving into how to do it right, let’s look at <strong>what to avoid</strong>:</p><h3>❌ Real Example #1: Nitpicking Comments</h3><blockquote><em>“You missed a semicolon.”<br> “Add a newline at the end.”</em></blockquote><p>While consistency is important, <strong>overly focusing on minor stylistic issues</strong> without adding real value is unproductive. Let linters and formatters handle this.</p><h3>❌ Real Example #2: Delayed Reviews</h3><blockquote><em>A PR sits open for 4 days because no one feels responsible for reviewing it.</em></blockquote><p>Delays kill momentum. A lack of ownership signals that the team doesn’t value collaboration.</p><h3>❌ Real Example #3: Vague or Harsh Feedback</h3><blockquote><em>“This makes no sense.”<br> “Why would you even do it like this?”</em></blockquote><p>This kind of feedback is not only unhelpful — it’s demoralizing. Code reviews should never be personal.</p><h3>✅ How to Do Code Reviews Right</h3><h3>1. Be Timely</h3><p>Set an internal SLA for reviews. For example:<br> ⏱ <em>Review all PRs within 24 hours.</em></p><h3>2. Be Respectful and Constructive</h3><p>Use empathy. Assume good intent.</p><p>✅ Real Example:</p><blockquote><em>“I like this approach! One suggestion: Would it be clearer if we extracted this into a helper method?”</em></blockquote><h3>3. Review the Bigger Picture</h3><p>Instead of just focusing on syntax, ask:</p><ul><li>Does this code align with the feature requirements?</li><li>Is it performant and scalable?</li><li>Are there security or edge case risks?</li></ul><h3>4. Don’t Be a Gatekeeper — Be a Collaborator</h3><p>Offer suggestions, not commands.</p><p>✅ Real Example:</p><blockquote><em>“This is working well. I wonder if using a service object here would help us reuse this logic later. What do you think?”</em></blockquote><h3>5. Use Tools for the Small Stuff</h3><p>Let linters, formatters, and CI pipelines handle:</p><ul><li>Style enforcement (e.g., RuboCop, ESLint)</li><li>Tests</li><li>Code formatting (e.g., Prettier, Black)</li></ul><h3>6. Explain the “Why”</h3><p>When suggesting changes, explain the reasoning.</p><p>✅ Real Example:</p><blockquote><em>“This method works, but </em><em>find_by is better than </em><em>where.first for readability and intent clarity.&quot;</em></blockquote><h3>7. Encourage Questions and Mentorship</h3><p>Junior developers should feel safe asking:</p><blockquote><em>“Why is this pattern better?”<br> “Is there a better way to structure this?”</em></blockquote><p>That’s how you <strong>grow talent</strong> on your team.</p><h3>🛠 Best Practices to Build a Strong Code Review Culture</h3><ul><li>✅ <strong>Set clear guidelines</strong> on what to check (performance, security, readability, etc.)</li><li>✅ <strong>Create a checklist</strong> (automated or manual) for common review points</li><li>✅ <strong>Keep PRs small</strong> — smaller PRs are faster to review and less prone to error</li><li>✅ <strong>Rotate reviewers</strong> to avoid bottlenecks and encourage knowledge sharing</li><li>✅ <strong>Celebrate good code</strong>, not just errors</li></ul><h3>📚 Example Code Review Workflow</h3><blockquote><em>👩‍💻 Dev A opens a PR: </em>“Add search functionality for users”</blockquote><blockquote><em>✅ PR size: ~200 lines<br>✅ Includes tests and updated documentation<br>✅ Dev B reviews within 6 hours</em></blockquote><p><strong>Review Comments from Dev B:</strong></p><ul><li>“This is cleanly written! 👏”</li><li>“Consider using ILIKE for case-insensitive search in Postgres.&quot;</li><li>“What happens if there are no users returned? Maybe we should return a helpful message to the frontend.”</li></ul><p>PR gets merged in 1 day. Dev A thanks Dev B for the helpful suggestions. Both grow a little bit as developers. That’s code review culture done right.</p><h3>✨ Final Thoughts</h3><p>Code reviews are not just about better code — they’re about <strong>better teams</strong>.</p><p>A strong code review culture:</p><ul><li>Builds trust</li><li>Spreads knowledge</li><li>Reduces bugs</li><li>Makes developers proud of their work</li></ul><p>Let’s stop treating code reviews as chores, and start using them as <strong>opportunities to grow together</strong>.</p><p><strong>LinkedIn :-</strong> <a href="https://www.linkedin.com/in/vaibhav-jain-6454971a4">https://www.linkedin.com/in/vaibhav-jain-6454971a4</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b1129bf9bdad" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Docker vs Kubernetes: When to Use What]]></title>
            <link>https://vaibhavdjain.medium.com/docker-vs-kubernetes-when-to-use-what-b63b874ccd83?source=rss-8aca5e6f75d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/b63b874ccd83</guid>
            <category><![CDATA[docker]]></category>
            <category><![CDATA[devops]]></category>
            <category><![CDATA[docker-compose]]></category>
            <category><![CDATA[software-engineering]]></category>
            <category><![CDATA[kubernetes]]></category>
            <dc:creator><![CDATA[Vaibhav Jain]]></dc:creator>
            <pubDate>Wed, 28 May 2025 11:55:58 GMT</pubDate>
            <atom:updated>2025-05-28T12:21:34.253Z</atom:updated>
            <content:encoded><![CDATA[<p>In the world of modern DevOps and cloud-native development, <strong>Docker</strong> and <strong>Kubernetes</strong> are two names you’ll encounter often — and sometimes, confusingly together. While both are related to containers, they serve very different purposes. In this article, we’ll break down the core differences between Docker and Kubernetes, and help you decide when to use what.</p><h3>🚢 What is Docker?</h3><p><strong>Docker</strong> is a platform designed to <strong>create, deploy, and run applications using containers</strong>. Containers are lightweight, portable packages that bundle your application code with its dependencies — ensuring consistency across environments.</p><p><strong>Key Features:</strong></p><ul><li>Easy containerization of applications</li><li>Lightweight and fast compared to traditional virtual machines</li><li>Supports isolation and reproducibility</li></ul><p><strong>When to Use Docker:</strong></p><ul><li>You’re developing microservices or containerized apps</li><li>You want consistency between local development and production</li><li>You need a lightweight environment for testing and deployment</li><li>Your application needs to run in multiple environments (local, cloud, on-prem)</li></ul><h3>☸️ What is Kubernetes?</h3><p><strong>Kubernetes</strong> (also known as <strong>K8s</strong>) is a <strong>container orchestration platform</strong>. Think of it as the operating system for your containerized applications. It helps you deploy, scale, and manage containers — especially across clusters of machines.</p><p><strong>Key Features:</strong></p><ul><li>Automated deployment, scaling, and operations of containerized apps</li><li>Self-healing (automatic restarts, replacements, and rescheduling)</li><li>Load balancing and service discovery</li><li>Secrets and configuration management</li></ul><p><strong>When to Use Kubernetes:</strong></p><ul><li>You’re managing <strong>many containers across multiple hosts</strong></li><li>You need <strong>automatic scaling</strong> and <strong>self-healing</strong> for your apps</li><li>You want <strong>rolling updates</strong> or <strong>zero-downtime deployments</strong></li><li>You’re dealing with <strong>production-grade workloads</strong> at scale</li></ul><h3>🔍 Docker vs Kubernetes: Not a Competition</h3><p>It’s important to understand that <strong>Docker and Kubernetes are not competitors</strong> — in fact, they often work together.</p><ul><li><strong>Docker</strong> helps you <em>build</em> and <em>run</em> containers.</li><li><strong>Kubernetes</strong> helps you <em>manage</em> and <em>orchestrate</em> those containers at scale.</li></ul><p>In many production setups, developers use <strong>Docker to create containers</strong> and then <strong>Kubernetes to orchestrate them</strong>.</p><h3>🤔 Choosing the Right Tool</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/915/1*MloSWLdOWP5ZXpTHdKBLTQ.png" /></figure><h3>🔄 Complementary, Not Exclusive</h3><p>It’s not about <strong>Docker vs Kubernetes</strong> — it’s about <strong>Docker AND Kubernetes</strong> when you’re working on cloud-native, scalable systems. Docker gets you started, Kubernetes helps you grow.</p><h3>🚀 Final Thoughts</h3><p>If you’re new to containers, <strong>start with Docker</strong>. Once you reach a point where managing multiple containers becomes complex, <strong>introduce Kubernetes</strong> into your workflow. Like any tool, the best choice depends on your specific needs, team size, and infrastructure complexity.</p><p>Got a small app? Stick with Docker. Running a production-grade service with multiple microservices? Kubernetes is your friend.</p><p><strong>Containers are the future. Choosing the right tools to manage them is the key.</strong></p><p><strong>LinkedIn :-</strong> <a href="https://www.linkedin.com/in/vaibhav-jain-6454971a4">https://www.linkedin.com/in/vaibhav-jain-6454971a4</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b63b874ccd83" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Single-Threaded vs Multi-Threaded in Ruby on Rails ]]></title>
            <link>https://vaibhavdjain.medium.com/single-threaded-vs-multi-threaded-in-ruby-on-rails-1d73dd4b0be4?source=rss-8aca5e6f75d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/1d73dd4b0be4</guid>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[web]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[rails]]></category>
            <dc:creator><![CDATA[Vaibhav Jain]]></dc:creator>
            <pubDate>Fri, 28 Feb 2025 09:19:25 GMT</pubDate>
            <atom:updated>2025-03-02T18:39:48.255Z</atom:updated>
            <content:encoded><![CDATA[<p>Ruby on Rails <strong>by default</strong> runs <strong>single-threaded</strong>, but it <strong>can be multi-threaded</strong> depending on the web server and configuration.</p><h3>🔹 1️⃣ What is Single-Threaded in Rails?</h3><p>📌 <strong>Definition:</strong></p><ul><li>A <strong>single-threaded</strong> Rails application <strong>processes only one request at a time per worker</strong>.</li><li>If one request is slow, others must <strong>wait</strong> until it finishes.</li></ul><p>📌 <strong>How It Works:</strong></p><ul><li>The <strong>default Ruby MRI (Matz’s Ruby Interpreter) has a Global Interpreter Lock (GIL)</strong>, meaning <strong>only one thread</strong> executes Ruby code at a time.</li><li>Even if you enable multiple threads, <strong>Ruby’s GIL prevents true parallel execution</strong> of Ruby code.</li></ul><p>📌 <strong>Example of Single-Threaded Execution:</strong><br> Imagine two users request a page. In <strong>single-threaded Rails</strong>, the second request <strong>must wait</strong> until the first is completed.</p><pre>Request 1  ───► Process ───► Response (Takes 2s)<br>Request 2  ───► WAIT ───► Process ───► Response (Takes 2s)</pre><p>⏳ <strong>Total time: 4s for both requests</strong></p><p>📌 <strong>When is Single-Threading Used?</strong></p><ul><li>If running Rails with <strong>WEBrick</strong> (default Rails server).</li><li>If using <strong>only process-based scaling (e.g., Unicorn without threads)</strong>.</li></ul><h3>🔹 2️⃣ What is Multi-Threaded in Rails?</h3><p>📌 <strong>Definition:</strong></p><ul><li><strong>Multi-threaded Rails</strong> can handle <strong>multiple requests at the same time within a single process</strong>.</li><li>Each request runs in a separate thread, improving concurrency.</li></ul><p>📌 <strong>How It Works:</strong></p><ul><li><strong>Puma</strong> (default server in Rails) allows multiple threads per worker.</li><li>If one request is waiting (e.g., for the database), another request can still be processed.</li></ul><p>📌 <strong>Example of Multi-Threaded Execution (2 Threads):</strong></p><pre>Request 1  ───► Thread 1 ───► Response (Takes 2s)<br>Request 2  ───► Thread 2 ───► Response (Takes 2s)</pre><p>✅ <strong>Total time: 2s for both requests (instead of 4s)</strong></p><p>📌 <strong>When is Multi-Threading Used?</strong></p><ul><li>If running Rails with <strong>Puma (</strong><strong>threads 5,5) or Passenger Enterprise</strong>.</li><li>If using <strong>ActiveRecord connection pooling (</strong><strong>pool: 10 in </strong><strong>database.yml)</strong>.</li><li>If the app is mostly <strong>I/O-bound (waiting on DB, API, etc.)</strong>, multi-threading helps.</li></ul><h3>🔹 3️⃣ Should You Use Multi-Threading in Rails?</h3><p>✅ <strong>Use Multi-Threading If:</strong></p><ul><li>Your app <strong>handles many concurrent requests</strong> (like APIs).</li><li>You use <strong>Puma or Passenger</strong> and enable threading (threads 5,5).</li><li>You want to <strong>improve response time and CPU utilization</strong>.</li></ul><p>❌ <strong>Avoid Multi-Threading If:</strong></p><ul><li>You are using <strong>MRI Ruby</strong> and do a lot of <strong>CPU-heavy work</strong> (GIL limits benefits).</li><li>Your app <strong>modifies shared memory</strong> (can cause race conditions).</li><li>You <strong>don’t properly configure DB connection pooling</strong> (can cause deadlocks).</li></ul><h3>🔹 4️⃣ How to Enable Multi-Threading in Rails?</h3><p>✅ <strong>Use Puma &amp; Configure Threads (</strong><strong>config/puma.rb):</strong></p><pre># Allow Puma to handle multiple threads<br>threads 5, 5<br>workers 2 # Enables multi-process as well<br>preload_app!</pre><p>✅ <strong>Optimize Database Connection Pooling (</strong><strong>config/database.yml):</strong></p><pre>production:<br>  adapter: postgresql<br>  pool: 10 # Should match or exceed thread count</pre><p>✅ <strong>Move Heavy Work to Background Jobs:</strong></p><pre>MyJob.perform_later(user) # Use Sidekiq for better thread safety</pre><h3>🏆 Final Verdict: Should Rails Be Single or Multi-Threaded?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/923/1*YKJNnv_BU67mi7Uhj_BneQ.png" /></figure><p>🚀 <strong>Multi-threading (with Puma) is recommended for most Rails apps, unless you have CPU-bound tasks.</strong></p><h3>🔹 How CPU Cores and Threads Work in Multi-Threading</h3><p>A <strong>CPU core</strong> is a <strong>physical processing unit</strong>, while a <strong>thread</strong> is a <strong>virtual unit of execution</strong> managed by the CPU. Modern CPUs support <strong>multi-threading</strong> (Hyper-Threading in Intel), where <strong>one core can handle multiple threads</strong>.</p><h3>1️⃣ How CPU Divides Work Among Threads</h3><p>🔹 If you have a <strong>4-core CPU</strong> and <strong>each core supports 2 threads</strong>, your system can handle <strong>8 concurrent threads</strong> at maximum.<br> 🔹 <strong>Threads are managed by the CPU scheduler</strong>, which assigns execution time to each thread.<br> 🔹 If your application creates <strong>more threads than available CPU threads</strong>, the system uses <strong>time slicing</strong>, where each thread gets a small time slot to execute before switching to the next one.</p><h3>2️⃣ What Happens If You Have More Threads Than CPU Cores?</h3><h3>Example: 4-Core CPU with 8 Threads Available</h3><p><strong>Scenario 1: The application uses only 4 threads</strong><br> ✅ <strong>Each thread runs on a separate core → No context switching → Best performance</strong></p><p><strong>Scenario 2: The application uses 8 threads (same as CPU limit)</strong><br> ✅ <strong>Each thread gets its own CPU thread → Good performance, but may have some contention</strong></p><p><strong>Scenario 3: The application uses 16+ threads (More than CPU limit)</strong><br> ⏳ <strong>The OS must schedule and switch threads constantly → Overhead increases → Slower performance</strong></p><h3>3️⃣ How Thread Scheduling Works When Threads &gt; CPU Cores?</h3><p>When an application has <strong>more threads than available CPU threads</strong>, the OS scheduler follows these steps:</p><p>1️⃣ <strong>Each CPU core gets assigned a certain number of threads</strong><br>2️⃣ <strong>The OS time-slices the execution</strong> (e.g., a thread runs for a few milliseconds, then another thread takes over)<br>3️⃣ <strong>Context switching occurs</strong>, where the CPU <strong>saves the state of one thread and loads another</strong><br>4️⃣ <strong>More threads = More switching overhead</strong>, which slows down execution</p><h3>🔹 Visual Representation (4-Core CPU, 8 Threads, 16 Application Threads)</h3><pre>Physical CPU Cores:  1   2   3   4  <br>Logical Threads:     1 2 3 4 5 6 7 8  <br>Application Threads: A B C D E F G H I J K L M N O P  <br>Time Slice 1:        A B C D (E, F, G, H are waiting)  <br>Time Slice 2:        E F G H (A, B, C, D are waiting)  <br>Time Slice 3:        I J K L (M, N, O, P are waiting)  <br>Time Slice 4:        M N O P (I, J, K, L are waiting)</pre><p>🚀 <strong>Conclusion:</strong> The more threads you have beyond CPU limits, the more time is wasted on <strong>context switching</strong>, reducing efficiency.</p><h3>4️⃣ How to Optimize Rails Multi-Threading Based on CPU?</h3><p>✅ <strong>If CPU has 4 cores &amp; 8 threads, configure Puma like this (</strong><strong>config/puma.rb)</strong></p><pre>workers 2     # Two processes (Each process uses multiple threads)<br>threads 4, 4  # Each process has 4 threads (Total: 2×4 = 8 threads)</pre><ul><li><strong>Workers use separate CPU cores</strong> (good for multi-core systems).</li><li><strong>Threads improve concurrency without excessive context switching.</strong></li></ul><h3>🏆 Final Takeaway: How Many Threads Should You Use?</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/933/1*DfOxPSgEuQ8y-EYTkPE4Ag.png" /></figure><p>🚀 <strong>Golden Rule:</strong> Keep Puma <strong>threads per worker ≤ CPU threads per core</strong> to avoid too much context switching!</p><p><strong>LinkedIn :-</strong> <a href="https://www.linkedin.com/in/vaibhav-jain-6454971a4">https://www.linkedin.com/in/vaibhav-jain-6454971a4</a></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/256/1*lAiZJA5ZELNCRHT_dG6fBQ.jpeg" /></figure><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1d73dd4b0be4" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[What are Rails engines? How to creating and integrating one?]]></title>
            <link>https://vaibhavdjain.medium.com/what-are-rails-engines-how-to-creating-and-integrating-one-873ba9c36cc8?source=rss-8aca5e6f75d4------2</link>
            <guid isPermaLink="false">https://medium.com/p/873ba9c36cc8</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails-development]]></category>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[rails-6]]></category>
            <dc:creator><![CDATA[Vaibhav Jain]]></dc:creator>
            <pubDate>Thu, 26 Dec 2024 12:31:26 GMT</pubDate>
            <atom:updated>2024-12-26T12:31:26.005Z</atom:updated>
            <content:encoded><![CDATA[<p><strong>Rails engines</strong> are essentially miniature Rails applications that can be mounted within a larger Rails application. They allow you to encapsulate specific functionality, making it reusable and modular. Engines are particularly useful when you want to develop features that can be shared across multiple Rails applications, such as authentication, payment processing, or any domain-specific logic.</p><h3>Key Features of Rails Engines:</h3><ol><li><strong>Self-contained</strong>: They have their own MVC components, routes, migrations, and assets.</li><li><strong>Mountable</strong>: You can mount an engine in a host application using the mount method in the routes.rb file.</li><li><strong>Reusable</strong>: Once developed, they can be packaged as gems and reused across projects.</li><li><strong>Customizable</strong>: Host applications can override or extend the functionality provided by the engine.</li></ol><h3>Types of Rails Engines:</h3><ol><li><strong>Full Engine</strong>: Includes its own application structure, such as controllers, models, views, helpers, and routes.</li><li><strong>Dummy Engine</strong>: Acts as a testing or development application for the engine. It is typically located in test/dummy or spec/dummy.</li></ol><h3>Here’s a detailed explanation of Rails engines, along with code snippets for <strong>creating</strong> and <strong>integrating</strong> a Rails engine:</h3><h3>Creating a Rails Engine</h3><p>To create a Rails engine, use the rails plugin new command with the <br>--mountable flag.</p><h4>Steps:</h4><ol><li><strong>Generate the Engine:</strong></li></ol><pre>rails plugin new my_engine --mountable</pre><p>This creates a directory named my_engine with a structure similar to a Rails app but scoped to the engine.</p><p><strong>2. Define Engine-Specific Functionality:</strong></p><ul><li>Open the lib/my_engine/engine.rb file:</li></ul><pre>module MyEngine<br>  class Engine &lt; ::Rails::Engine<br>    isolate_namespace MyEngine<br>  end<br>end</pre><ul><li>The isolate_namespace ensures that the engine’s routes, controllers, and helpers don’t clash with the main application.</li></ul><p><strong>3. Add Models, Controllers, and Routes:</strong></p><ul><li>Add a sample model:</li></ul><pre># app/models/my_engine/post.rb<br>module MyEngine<br>  class Post &lt; ApplicationRecord<br>  end<br>end</pre><ul><li>Create a controller:</li></ul><pre># app/controllers/my_engine/posts_controller.rb<br>module MyEngine<br>  class PostsController &lt; ApplicationController<br>    def index<br>      @posts = Post.all<br>    end<br>  end<br>end</pre><ul><li>Define routes:</li></ul><pre># config/routes.rb<br>MyEngine::Engine.routes.draw do<br>  resources :posts<br>end</pre><p><strong>4. Prepare Dummy App for Testing:</strong> A dummy Rails app is created in test/dummy or spec/dummy to test the engine.</p><p><strong>5. Bundle the Engine:</strong> Package the engine as a gem and add it to other projects.</p><h3>Integrating a Rails Engine</h3><p>To integrate an engine, you need to mount it in a host Rails application.</p><h4>Steps:</h4><ol><li><strong>Add the Engine to the Host App:</strong> Add the engine to the Gemfile:</li></ol><pre>gem &#39;my_engine&#39;, path: &#39;../my_engine&#39; #Local path</pre><p>Or use a remote source:</p><pre>gem &#39;my_engine&#39;, git: &#39;https://github.com/username/my_engine.git&#39;</pre><p><strong>2. Bundle Install:</strong> Run bundle install to load the engine.</p><p><strong>3. Mount the Engine:</strong> Mount the engine in the routes.rb file:</p><pre>Rails.application.routes.draw do<br>  mount MyEngine::Engine, at: &quot;/my_engine&quot;<br>end</pre><p><strong>4. Access the Engine:</strong> Once mounted, the engine’s routes are available at the specified path (/my_engine in this case). For example, navigating to /my_engine/posts will access the PostsController from the engine.</p><h3>Testing the Integration</h3><p>After mounting the engine, ensure that it works by accessing its routes in the browser or running the test suite included with the engine.</p><p>Let’s dive deeper into <strong>packaging a Rails engine as a gem</strong> and <strong>extending its functionality</strong> in a host application.</p><h3>1. Packaging a Rails Engine as a Gem</h3><p>A Rails engine can be distributed as a gem, making it easy to reuse across multiple applications.</p><h3>Steps to Package the Engine as a Gem</h3><ol><li><strong>Ensure the </strong><strong>gemspec is Correct</strong> The gemspec file is auto-generated when the engine is created. Open my_engine.gemspec and update its metadata:</li></ol><pre>Gem::Specification.new do |s|<br>  s.name        = &quot;my_engine&quot;<br>  s.version     = &quot;0.1.0&quot;<br>  s.summary     = &quot;A sample Rails engine&quot;<br>  s.description = &quot;Provides reusable functionality for managing posts&quot;<br>  s.authors     = [&quot;Your Name&quot;]<br>  s.email       = [&quot;your_email@example.com&quot;]<br>  s.files       = Dir[&quot;{app,config,db,lib}/**/*&quot;, &quot;MIT-LICENSE&quot;, &quot;Rakefile&quot;, &quot;README.md&quot;]<br>  s.homepage    = &quot;https://github.com/your_username/my_engine&quot;<br>  s.license     = &quot;MIT&quot;<br>end</pre><p><strong>2. Add Dependencies (if any)</strong> If your engine relies on specific gems, declare them in the gemspec:</p><pre>s.add_dependency &quot;rails&quot;, &quot;~&gt; 7.0&quot;<br>s.add_dependency &quot;devise&quot;, &quot;~&gt; 4.8&quot;</pre><p><strong>3. Build the Gem</strong> From the engine’s root directory, build the gem:</p><pre>gem build my_engine.gemspec</pre><p>This creates a .gem file (e.g., my_engine-0.1.0.gem).</p><p><strong>4. Push the Gem to a Repository</strong> You can publish your gem to a repository like RubyGems or a private gem server.</p><ul><li><strong>To push to RubyGems</strong>:</li></ul><pre>gem push my_engine-0.1.0.gem</pre><p>If the gem is private, consider using a service like <a href="https://gemfury.com/">Gemfury</a> or host a private gem server.</p><p><strong>5. Install the Gem in Other Projects</strong> In your Gemfile, include the gem:</p><pre>gem &#39;my_engine&#39;, &#39;~&gt; 0.1.0&#39;</pre><p>Run bundle install to install it.</p><h3>2. Extending the Engine’s Functionality</h3><p>You can customize or override parts of the engine in the host application.</p><h3>Methods for Extending an Engine</h3><h4>A. Override Views</h4><p>Copy the engine’s views into the host app to customize them:</p><ol><li>Find the engine’s views (e.g., my_engine/app/views/my_engine/posts/index.html.erb).</li><li>Copy them into the host app’s corresponding directory:</li></ol><pre>app/views/my_engine/posts/index.html.erb</pre><p>3. Modify the views as needed.</p><h4>B. Override Controllers</h4><p>Use Rails’ class_eval or inherit from the engine&#39;s controllers:</p><ol><li>Create a new controller in the host app:</li></ol><pre>class MyEngine::PostsController &lt; ApplicationController<br>  def index<br>    @posts = MyEngine::Post.published<br>  end<br>end</pre><p>2. Ensure the routes point to the overridden controller.</p><h4>C. Add Custom Routes</h4><p>Extend the engine’s routes in the host app:</p><ol><li>Use the draw method in config/routes.rb:</li></ol><pre>Rails.application.routes.draw do<br>  mount MyEngine::Engine, at: &quot;/my_engine&quot;<br>  MyEngine::Engine.routes.draw do<br>    get &#39;custom_route&#39;, to: &#39;posts#custom_action&#39;<br>  end<br>end</pre><h4>D. Override Models</h4><p>Extend or customize models using Ruby’s prepend or class_eval:</p><ol><li>In the host app, add a decorator (e.g., app/models/my_engine/post_decorator.rb):</li></ol><pre>MyEngine::Post.class_eval do<br>  scope :published, -&gt; { where(published: true) }<br>end</pre><h4>E. Add Initializers</h4><p>Add custom configuration for the engine in the host app’s config/initializers/ directory:</p><pre># config/initializers/my_engine.rb<br>MyEngine.configure do |config|<br>  config.some_setting = &quot;custom_value&quot;<br>end</pre><h3>Best Practices</h3><ol><li><strong>Keep the Engine Modular:</strong> Encapsulate logic within the engine to reduce dependencies on the host app.</li><li><strong>Document Customization Options:</strong> Provide clear instructions for overriding views, controllers, and configurations.</li><li><strong>Use Versioning:</strong> Follow semantic versioning to communicate changes to users of the gem.</li><li><strong>Avoid Hardcoding URLs:</strong> Use named routes or configuration options to make the engine flexible.</li></ol><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=873ba9c36cc8" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>