<?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 Rutvik Chandla on Medium]]></title>
        <description><![CDATA[Stories by Rutvik Chandla on Medium]]></description>
        <link>https://medium.com/@rutvikchandla3?source=rss-6a68ff3ffe76------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*jiKIknnjjoyLVGNpo7GuCg.jpeg</url>
            <title>Stories by Rutvik Chandla on Medium</title>
            <link>https://medium.com/@rutvikchandla3?source=rss-6a68ff3ffe76------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 16 Nov 2026 05:31:49 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@rutvikchandla3/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[10x cheaper LLM tokens, but how?]]></title>
            <link>https://medium.com/@rutvikchandla3/10x-cheaper-llm-tokens-but-how-c1c1795a3b88?source=rss-6a68ff3ffe76------2</link>
            <guid isPermaLink="false">https://medium.com/p/c1c1795a3b88</guid>
            <category><![CDATA[llm]]></category>
            <category><![CDATA[ai]]></category>
            <category><![CDATA[llm-inference]]></category>
            <category><![CDATA[claude]]></category>
            <category><![CDATA[prompt-caching]]></category>
            <dc:creator><![CDATA[Rutvik Chandla]]></dc:creator>
            <pubDate>Sat, 18 Apr 2026 16:27:14 GMT</pubDate>
            <atom:updated>2026-04-18T16:27:14.870Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8Y5SJeDstpXPfP2cyHIo3g.png" /><figcaption>LLM Prompt Caching</figcaption></figure><h3>TL;DR, just give me the code</h3><p>If you’re here only for<em> “which field do I add”</em>, here you go. Bookmark and leave.</p><h4>Claude —</h4><pre># ONE field. cache_control on the LAST block of your static prefix.<br>curl https://api.anthropic.com/v1/messages \<br>  -H &quot;x-api-key: $ANTHROPIC_API_KEY&quot; \<br>  -H &quot;anthropic-version: 2023-06-01&quot; \<br>  -d &#39;{<br>    &quot;model&quot;: &quot;claude-sonnet-4-5&quot;,<br>    &quot;max_tokens&quot;: 1024,<br>    &quot;system&quot;: [<br>      { &quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;You are a helpful assistant.&quot; },<br>      {<br>        &quot;type&quot;: &quot;text&quot;,<br>        &quot;text&quot;: &quot;&lt;BIG_STATIC_CONTEXT_HERE&gt;&quot;,<br>        &quot;cache_control&quot;: { &quot;type&quot;: &quot;ephemeral&quot; }<br>      }<br>    ],<br>    &quot;messages&quot;: [{ &quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;hi&quot; }]<br>  }&#39;</pre><h4>OpenAI —</h4><pre># Nothing. Caching is AUTOMATIC for prompts &gt;= 1024 tokens.<br># Just keep static stuff at the TOP. Optionally set prompt_cache_key.<br>curl https://api.openai.com/v1/responses \<br>  -H &quot;Authorization: Bearer $OPENAI_API_KEY&quot; \<br>  -d &#39;{<br>    &quot;model&quot;: &quot;gpt-5.1&quot;,<br>    &quot;input&quot;: &quot;&lt;BIG_STATIC_CONTEXT&gt;\n\nUser: hi&quot;,<br>    &quot;prompt_cache_key&quot;: &quot;tenant-42&quot;,<br>    &quot;prompt_cache_retention&quot;: &quot;24h&quot;<br>  }&#39;</pre><p>Yep, for GPT you literally don’t add anything.</p><blockquote><em>If you want to actually </em><strong><em>understand</em></strong><em> what’s happening under the hood and not just copy-paste, stick around till the end. That’s where the fun part is.</em></blockquote><h3>So what even is Prompt Caching?</h3><p>Every API call to an LLM, you’re shipping the same boring prefix over and over.</p><ul><li>2k token system prompt</li><li>20 few-shot examples</li><li>The full chat history</li><li>And finally the actual new user message</li></ul><p>And the model re-reads ALL of it. Every time. Which means you pay for it, every time.</p><blockquote>Prompt caching says: “I saw this same prefix 30 seconds ago, let me just pick up where I left off.”</blockquote><p>Same prefix, re-use the computation. Pay ~10% of the price, get the answer back way faster.</p><h4>Wait, am I already using this?</h4><p>If you’re shipping through <strong>Claude Code, OpenCode, Codex, GitHub Copilot, Cursor</strong>, or honestly any half-decent agent harness, they are already doing prompt caching for you behind the scenes. That’s a big reason their token bills don’t spiral out of control even though they shove your entire codebase into every call. Ever noticed how the <em>first</em> message in a Claude Code session feels a bit slow and the next 10 are instant? Yep, that’s the cache warming up.</p><p>The ones who actually get bitten are engineers rolling their own LLM integration. Internal tools, custom agents, a RAG pipeline, that one Slack bot nobody owns. You wire up the Anthropic / OpenAI SDK directly, ship it, and 3 months later Finance sends a “hey wtf is this bill” email.</p><blockquote>If you’re calling the API directly, you own this. Nobody is caching for you.</blockquote><p>So this blog is mostly for the “rolling my own” crowd, or anyone curious about what their harness is doing under the hood.</p><h4>How is this even possible?</h4><p>Think of an LLM as a function that reads your prompt token by token, left to right. For each token it does a bunch of math and produces some intermediate state (a big vector of numbers). That state is what the model eventually uses to pick the next word.</p><p>Two facts about that process are what make caching possible:</p><ol><li><strong>The model only looks backward.</strong> When it processes token #5, it only uses tokens #1 through #4. It literally cannot peek at #6, #7, #8. This is called “causal” attention and it is baked into how these models are trained.</li><li><strong>The math is deterministic.</strong> Same input tokens in, same intermediate state out. Always.</li></ol><p>Put those together:</p><blockquote>If you send the same first 5,000 tokens twice, the intermediate state for those tokens is identical both times. So why recompute it?</blockquote><p>Basically it is memoization, at the model’s internal-state layer. The provider stashes that intermediate state (called the <strong>KV cache</strong>, short for Key/Value cache) in GPU memory. On your next request, if the first N tokens match what it already has saved, it skips recomputing them and picks up from token N+1.</p><pre>                       [ cached state          ]  [ new work ]<br>Request 1:   [system] [context] [examples] [hist] · [msg1]   ← compute + save<br>Request 2:   [system] [context] [examples] [hist] · [msg2]   ← reuse cache, only compute msg2<br>Request 3:   [system] [context] [examples] [hist] · [msg3]   ← reuse cache, only compute msg3</pre><p>One more thing. On a long prompt the expensive part of an LLM call is <strong>not</strong> generating the answer, it is processing the prompt itself. This stage is called “prefill” and it scales with prompt length. Cache that, you skip the whole thing. That’s where the 10x savings come from.</p><p>Two things to remember:</p><ol><li><strong>Caching is PREFIX-based.</strong> Change ONE token near the top, everything after it has to be recomputed, and the whole cache dies.</li><li><strong>Static stuff first, dynamic stuff last.</strong> Always. system → tools → examples → history → THEN new user message.</li></ol><h4>Claude, the explicit version</h4><p>Anthropic gives you <strong>control</strong>. You literally mark where the cache ends.</p><pre># pip install anthropic<br>from anthropic import Anthropic<br>client = Anthropic()<br><br>client.messages.create(<br>    model=&quot;claude-sonnet-4-5&quot;,<br>    max_tokens=1024,<br>    system=[<br>        {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: &quot;You are a Rails expert.&quot;},<br>        {<br>            &quot;type&quot;: &quot;text&quot;,<br>            &quot;text&quot;: open(&quot;huge_codebase_context.md&quot;).read(),<br>            &quot;cache_control&quot;: {&quot;type&quot;: &quot;ephemeral&quot;}   # ← THE magic line<br>        }<br>    ],<br>    messages=[{&quot;role&quot;: &quot;user&quot;, &quot;content&quot;: &quot;why is this test flaky?&quot;}]<br>)</pre><p>Everything up to and including the block with cache_control is the cached prefix. The user message comes <em>after</em>, so it&#39;s the only thing re-processed. Ah, self explanatory!</p><h4>Pricing (Sonnet 4.5, per 1M tokens)</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1018/1*D_y5jXS2UYlmdUeca7_FcQ.png" /></figure><blockquote><em>You pay 25% more on the FIRST request, then 90% less on every subsequent one. Break-even is basically 2 hits. After that, you just keep saving.</em></blockquote><h4>Minimum tokens to cache</h4><p>Claude silently refuses to cache if the prefix is too short:</p><ul><li>Sonnet 4.5 / Opus 4.1 → <strong>1024 tokens</strong></li><li>Sonnet 4.6 / Haiku 3.5 → <strong>2048 tokens</strong></li><li>Opus 4.5+ / Haiku 4.5 → <strong>4096 tokens</strong></li></ul><p>If both cache_creation_input_tokens AND cache_read_input_tokens are 0 in the response, you quietly didn&#39;t cache anything. No error, nothing. Silent miss.</p><h4>TTL</h4><ul><li>Default <strong>5 minutes</strong> (refreshed for free on every hit)</li><li>Optional <strong>1 hour</strong>, add &quot;ttl&quot;: &quot;1h&quot; inside cache_control (costs 2x on write)</li></ul><h4>Only 4 breakpoints per request</h4><p>Important limit: Claude gives you a <strong>maximum of 4</strong> cache_control breakpoints in a single request. Not 4 per system, not 4 per messages. <strong>4 total, across the entire request.</strong> Try to add a 5th, you get a 400 error.</p><p>That’s usually plenty, but useful to know when you want to cache different chunks that change at different frequencies:</p><pre>system=[<br>    {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: tools_doc,    &quot;cache_control&quot;: {&quot;type&quot;: &quot;ephemeral&quot;}},  # rarely changes<br>    {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: user_context, &quot;cache_control&quot;: {&quot;type&quot;: &quot;ephemeral&quot;}},  # daily<br>    {&quot;type&quot;: &quot;text&quot;, &quot;text&quot;: session_data, &quot;cache_control&quot;: {&quot;type&quot;: &quot;ephemeral&quot;}},  # per-session<br>]<br># You have 1 slot left if you also want to mark something inside messages[].</pre><h4>The #1 mistake</h4><p>Slapping cache_control on a block that changes every request. Timestamps, current user message, a &quot;now(): ...&quot; string.</p><blockquote><em>Cache writes happen ONLY at the breakpoint. If the breakpoint block itself changes, the hash changes, and no prior write is ever reused.</em></blockquote><p>Move the breakpoint to the <em>last block that’s identical</em> across requests. That is THE rule.</p><h4>OpenAI, the automatic version</h4><p>OpenAI took a different bet: caching happens automatically, nothing to opt into.</p><p><em>No code change.</em> Seriously. Any prompt ≥ 1024 tokens on gpt-4o or newer is cached automatically. No field, no header, nothing.</p><pre># just... call the API normally<br>client.responses.create(<br>    model=&quot;gpt-5.1&quot;,<br>    input=big_static_prefix + user_message,<br>)</pre><p>Check if it actually hit:</p><pre>&quot;usage&quot;: {<br>  &quot;prompt_tokens&quot;: 2006,<br>  &quot;prompt_tokens_details&quot;: { &quot;cached_tokens&quot;: 1920 }   // look here<br>}</pre><p>Cached input tokens are billed at <strong>~50% off</strong> input price. No cache-write premium like Claude, no extra config, no extra cost.</p><h4>Two optional knobs</h4><p><strong>1. </strong><strong>prompt_cache_key</strong>, a hint to the router so identical-prefix requests land on the same machine:</p><p>Rule of thumb: keep each unique (prefix + cache_key) combo under ~15 req/min, otherwise they overflow to other machines and hit rate drops.</p><p><strong>2. </strong><strong>prompt_cache_retention</strong>, extend the TTL:</p><p>Default is in_memory (5 to 10 min, up to 1h). &quot;24h&quot; offloads the K/V tensors to GPU-local storage for up to a day. <strong>Same price</strong>, just longer life. Available on gpt-5.x and gpt-4.1.</p><blockquote><em>Cache hits are </em><strong><em>exact prefix matches</em></strong><em>. Static content at the top. Dynamic content at the bottom.</em></blockquote><p>Sounds obvious. Still the #1 reason devs get 0% cache hit rate. If your system prompt contains &quot;Current date: 2026-04-18 14:32:07&quot; at the top, congrats, every request is a fresh miss.</p><h4>Gotchas across both providers</h4><ul><li><strong>Images</strong>. Both support caching them, but bytes + detail param must be byte-identical.</li><li><strong>Tool definitions</strong> are part of the cache. Changing ONE description invalidates the whole tools cache.</li><li><strong>JSON key order</strong> in tool-use blocks can break caches in some languages (Swift, Go randomise keys). Sort your keys.</li><li><strong>Parallel requests</strong>. The first one hasn’t finished writing the cache yet, so concurrent siblings will also miss. Fire one, wait, then fan out.</li><li><strong>Org isolation</strong>. No, you can’t “steal” someone else’s cache. Different orgs never share.</li></ul><h4>Closing</h4><p><strong>Quick recap:</strong></p><ul><li><strong>Claude</strong> → one cache_control: { type: &quot;ephemeral&quot; } on the last stable block. You&#39;re the driver.</li><li><strong>GPT</strong> → put static stuff first. That’s it. It just works.</li><li><strong>Both</strong> → it’s <strong>prefix</strong> caching, not semantic caching. Change one token near the top, cache gone.</li><li><strong>Using Claude Code / Copilot / Cursor?</strong> → you’re already covered, go touch grass.</li><li><strong>Building your own agent / RAG / bot?</strong> → this is on YOU. Don’t skip it.</li></ul><p>Ohh damn, you made it here. Dedication!! If this saved you some Anthropic/OpenAI dollars, <strong>follow</strong> and leave a 👏, gives me extra motivation to keep writing :)</p><blockquote>Upcoming blog: building a request-level cache layer around your LLM SDK (cache prompt → response pairs for zero-cost replays on repeat queries).</blockquote><p>Also <strong>subscribe</strong> if the content is useful, THANKS ALL!!</p><p>If you’re building LLM infra and want me to audit your prompt’s cache strategy, hit me up on <a href="https://x.com/RUTVIKCHANDLA">X</a>. Weirdly fun puzzle.</p><p><strong>[ References ]</strong></p><ul><li>Anthropic: <a href="https://platform.claude.com/docs/en/build-with-claude/prompt-caching">https://platform.claude.com/docs/en/build-with-claude/prompt-caching</a></li><li>OpenAI: <a href="https://developers.openai.com/api/docs/guides/prompt-caching">https://developers.openai.com/api/docs/guides/prompt-caching</a></li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=c1c1795a3b88" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Heap Layout — Ruby]]></title>
            <link>https://medium.com/@rutvikchandla3/heap-layout-ruby-ecaa68d85a2d?source=rss-6a68ff3ffe76------2</link>
            <guid isPermaLink="false">https://medium.com/p/ecaa68d85a2d</guid>
            <category><![CDATA[ruby]]></category>
            <dc:creator><![CDATA[Rutvik Chandla]]></dc:creator>
            <pubDate>Sun, 11 Aug 2024 09:16:26 GMT</pubDate>
            <atom:updated>2024-08-12T07:52:24.775Z</atom:updated>
            <content:encoded><![CDATA[<h3>Heap Layout — Ruby</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/882/1*HhWlruqJ7r30zrCKN9qh_w.png" /></figure><h3>Introduction</h3><p>To understand Memory Leak, Memory Bloat or External Heap fragmentation — understanding of “How ruby stores object inside heap?” is crucial.</p><h3>Layout Overview</h3><p>Typically ruby allocate objects in:</p><ul><li><strong>Ruby Heap</strong> (Ruby pages and slots) — we will cover this in blog</li><li><strong>Transient Heap</strong> (Secondary heap ruby-2.6+) — in upcoming blog</li><li><strong>External heap</strong> (allocate object using malloc)</li></ul><p>Ruby entities like RString, RHash, RClass are stored in Ruby heap.<br>At base level, everything starts with “Slot”</p><h4>Ruby Slot</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/739/1*9H4W0YpXFrp_RpLTKn-g9w.png" /><figcaption>ruby slot</figcaption></figure><p>So for example, for a string object</p><ul><li>If length ≤ 23 it will store the <strong>entire string as a value</strong></li><li>If length &gt; 23, it will do a <strong>malloc()</strong> to get chunk of system memory and inside slot’s value put <strong>memory address </strong>of malloc’ed chunk</li></ul><p>Slots are kept same size to remove memory fragmentation issue within page.</p><p>By fragmentation I meant, smaller gaps between large objects.</p><h4>Ruby Pages</h4><blockquote>Ruby and OS pages are different.</blockquote><p>Ruby Page = 16KB and OS page = 4KB. Ruby pages contains ruby slots:<br>Each page contains =&gt;16KB / 40B ~ 409 slots</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/571/1*Y9FvitIvGQmKcWhCY_OXpg.png" /></figure><p>Freelist is a linked-list Data Structure — to enable quick bump allocation of slots, which means “New slot” will be placed at head of freelist and head is moved to next.</p><h3>Ruby Heap</h3><p>Simply put Ruby Heap is <strong>collection</strong> of Ruby Pages.</p><p>The actual questions are — <br>“Why is the need of ruby slots and pages?”<br>“Can’t we just use malloc() and free() to store object values?”</p><p>I’m not a C++ dev, but few of the problems that can present by frequent malloc and free are</p><ul><li><strong>Performance overhead</strong> — Time for system to scout and allocate + fragmentation can happen as the memory will be non-contiguos blocks</li><li><strong>Memory leaks</strong> — free() call does not always actually free the memory space</li></ul><p>So at start of a program, ruby mallocs bunch of Ruby Pages which is used for storing objects on runtime.</p><h3>Transient heap</h3><blockquote>Will be covering this in my upcoming blog,<br>Main idea of this heap is to reduce the malloc calls to external heap.<br>This was introduced in ruby 2.6+</blockquote><h3><strong>External heap</strong></h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*g8oyzy6Fzn9lWz9kuu9jyg.png" /></figure><p>Keeping it short, as discussed in “Ruby Slot”, if object length is greate it does malloc and put value inside that address space.</p><p>This heap is maintained by (glibc / jemalloc) memory allocators, ruby just do malloc() and free() based on liveliness of objects.</p><p>That is it for this blog! Upcoming blogs —</p><ol><li>Transient Heap</li><li>Garbage collection in Ruby programs</li><li>Reduce Memory bloat, leak and fragmentation — Ruby on Rails</li></ol><p>I write about Ruby and Nodejs internals and performance if you are interested should consider follow and subscribe :)</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ecaa68d85a2d" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Render HTML from Database in Ruby and Rails]]></title>
            <link>https://medium.com/@rutvikchandla3/render-templates-from-database-in-rails7-459429ebbf0e?source=rss-6a68ff3ffe76------2</link>
            <guid isPermaLink="false">https://medium.com/p/459429ebbf0e</guid>
            <category><![CDATA[ruby-on-rails-development]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Rutvik Chandla]]></dc:creator>
            <pubDate>Sat, 27 Jul 2024 17:14:50 GMT</pubDate>
            <atom:updated>2024-08-01T16:23:38.862Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*AN_kRnPEvLyxsFF0I_VSuA.png" /></figure><h3>Prerequisites</h3><ul><li>You should be familiar with MVC architecture, especially with ruby on rails.</li><li>Read my previous <a href="https://medium.com/@rutvikchandla3/resolvers-in-ruby-and-rails-d3c9a38bbdba">blog</a> — Resolvers in Ruby and Rails.</li></ul><h3>Why even to care about CustomResolver?</h3><p>Companies like <strong>Shopify</strong> which have their main application stack as Rails and that renders almost different themes or sets of frontend view files for each users, should be using a more fancier version of this Custom Resolvers and if you have found this blog after googling you know there are no good resource related to this :(</p><p>So over and all, if you are some company who wants to server different frontend files based on different user this might help!</p><h3>Problem Statement 📝</h3><p>Instead of getting the templates from the filesystem i.e <em>app/views</em> directory, we want to store and fetch templates from other data sources like SQL DB / NO SQL DB.</p><h3>Some Thinking 💬</h3><p>There must be “something” in Rails, which is responsible to read the template and pass it to the Rails rendering service. We need to rewrite the fetching logic of “something”. Instead of filesystem we’ll make a sql query to our DB to get the content.</p><h3>Getting Pieces together 🧩</h3><p>“something” is <strong>Resolvers</strong> in Rails. I have covered <a href="https://medium.com/@rutvikchandla3/resolvers-in-ruby-and-rails-d3c9a38bbdba">here</a> in-depth what it is and what are main API (functions) that we need to re-write if we want to have a custom resolver.</p><p>Rails use <strong>FileSystemResolver </strong>to get the files, similarly we will write a resolver <strong>DynamicTemplate::Resolver </strong>that will fetch templates from DB</p><h3>Let Us Code It Out 💻</h3><p>We will make a simple CRUD application, the main focus will be on getting the templates from the DB (sqlite / default) instead of filesystem.</p><pre># Create a new rails application<br>rails new dynamicrenderer<br><br># Create a table in DB to store Content of the templates along with some metadata<br># DynamicTemplate will be a generic table that will store files for other entities<br>rails generate scaffold DynamicTemplate body:text path:string format:string locale:string handler:string partial:boolean<br><br># Generate a scaffold for Post entity -- <br># this will create Model + Controller + view files with basic CRUD controller actions<br>rails generate scaffold Post title:string description:text<br><br>bundle install<br>rails db:migrate RAILS_ENV=development</pre><p>With above we’ll have a basic CRUD application working.<br>Now, let us address the 🐘 in the room — Custom resolver</p><pre># app/models/dynamic_template.rb<br>class DynamicTemplate &lt; ApplicationRecord<br>... <br>  class Resolver &lt; ActionView::Resolver<br>    protected<br><br>    def find_templates(name, prefix, partial, details, locals = [])<br>      puts &quot;details: #{details}&quot;<br><br>      conditions = {<br>        path: normalize_path(name, prefix),<br>        locale: normalize_array(details[:locale]).first,<br>        format: [normalize_array(details[:formats]).first, &quot;html&quot;],<br>        handler: normalize_array(details[:handlers]),<br>        partial: partial || false<br>      }<br>      puts &quot;Conditions: #{conditions}, locals: #{locals}&quot;<br>      ::DynamicTemplate.where(conditions).map do |record|<br>        initialize_template(record, locals)<br>      end<br>    end<br><br>...<br><br>    # Initialize an ActionView::Template object based on the record found.<br>    def initialize_template(record, locals)<br>      source = record.body<br>      identifier = &quot;DynamicTemplate - #{record.id} - #{record.path.inspect}&quot;<br>      handler = ActionView::Template.registered_template_handler(record.handler)<br>      details = {<br>        format: Mime[record.format],<br>        virtual_path: virtual_path(record.path, record.partial)<br>      }<br>      puts &quot;details: #{details}&quot;<br>      ActionView::Template.new(<br>          source,<br>          identifier,<br>          handler,<br>          format: record.format.to_sym,<br>          virtual_path: details[:virtual_path],<br>          locals: locals.map(&amp;:to_s)<br>        )<br>    end<br>...<br>  end<br>end</pre><p>We can see the whole code <a href="https://github.com/RutvikChandla/dynamicrenderer/blob/main/app/models/dynamic_template.rb">here</a>, but the main thing that we need to focus on is:</p><ul><li>Which function is called in a Resolver by ActionView to get the templates?</li><li>What should be return type and data from our resolver?</li></ul><p>“find_templates” is the function that is called with all the params to any resolver and expected data class is ActionView::Template (<a href="https://github.com/rails/rails/blob/9826d743aec09b2f34ab0c20acf7270a1f081187/actionview/lib/action_view/unbound_template.rb#L50-L59">source</a>)</p><h3>Registering Custom Resolver to Controller</h3><p>Let us assume our <strong>DynamicTemplate::Resolver </strong>will work, next question is how we can tell a controller or rails to use our resolver instead of FilesystemResolver.</p><pre>class PostsController &lt; ApplicationController<br>  ...<br>  prepend_view_path DynamicTemplate::Resolver.new<br>  ...<br>end</pre><p>Controller have these hook <strong>prepend_view_path</strong> and <strong>append_view_path</strong>, which will add any custom resolver to list of resolver i.e [FileSystemResolver]</p><p>We are using prepend here so [ DynamicTemplate::Resolver.new, FileSystemResolver ] will be the list of Resolver which rails will iterate and call <strong>find_templates </strong>on them.</p><h3>Testing 🧪</h3><blockquote>Yes! I’m skipping the “unit test” way to test because who does that?? for a local project?? really??</blockquote><p>First thing will be to load out templates in our DB, open rails console and execute the below commands.</p><pre>app = DynamicTemplate.new({:path=&gt;&quot;layouts/application&quot;, :locale=&gt;&quot;en&quot;, :format=&gt;&quot;html&quot;, :handler=&gt;&quot;erb&quot;, :partial=&gt;false})<br>p =&quot;#{Rails.root.to_s}/app/views/layouts/applicationss.html.erb&quot;<br>app.body = File.read(p)<br>app.save!<br><br>app = DynamicTemplate.new({:path=&gt;&quot;posts/post&quot;, :locale=&gt;&quot;en&quot;, :format=&gt;&quot;html&quot;, :handler=&gt;&quot;erb&quot;, :partial=&gt;true})<br>p =&quot;#{Rails.root.to_s}/app/views/posts/_post.html.erb&quot;<br>app.body = File.read(p)<br>app.save!<br><br>app = DynamicTemplate.new({:path=&gt;&quot;posts/show&quot;, :locale=&gt;&quot;en&quot;, :format=&gt;&quot;html&quot;, :handler=&gt;&quot;erb&quot;, :partial=&gt;false})<br>p =&quot;#{Rails.root.to_s}/app/views/posts/show.html.erb&quot;<br>app.body = File.read(p)<br>app.save!<br><br>app = DynamicTemplate.new({:path=&gt;&quot;posts/index&quot;, :locale=&gt;&quot;en&quot;, :format=&gt;&quot;html&quot;, :handler=&gt;&quot;erb&quot;, :partial=&gt;false})<br>p =&quot;#{Rails.root.to_s}/app/views/posts/index.html.erb&quot;<br>app.body = File.read(p)<br>app.save!<br><br>app = DynamicTemplate.new({:path=&gt;&quot;posts/form&quot;, :locale=&gt;&quot;en&quot;, :format=&gt;&quot;html&quot;, :handler=&gt;&quot;erb&quot;, :partial=&gt;true})<br>p =&quot;#{Rails.root.to_s}/app/views/posts/_form.html.erb&quot;<br>app.body = File.read(p)<br>app.save!<br><br>app = DynamicTemplate.new({:path=&gt;&quot;posts/new&quot;, :locale=&gt;&quot;en&quot;, :format=&gt;&quot;html&quot;, :handler=&gt;&quot;erb&quot;, :partial=&gt;false})<br>p =&quot;#{Rails.root.to_s}/app/views/posts/new.html.erb&quot;<br>app.body = File.read(p)<br>app.save!</pre><p>Now take a <strong>TRUST FALL</strong> and delete “app/views/posts” directory from your filesystem.</p><p>NO SERIOUSLY - Delete the directory.</p><pre># run the rails server, default port is 3000<br>rails s</pre><p>Now, if you go to <a href="http://localhost:3000/posts">http://localhost:3000/posts</a>, you will see some logs as below, which is indicating that the content is getting loaded from the DB 👏</p><pre>DynamicTemplate Load (0.2ms)  SELECT &quot;dynamic_templates&quot;.* FROM &quot;dynamic_templates&quot; WHERE &quot;dynamic_templates&quot;.&quot;path&quot; = ? AND &quot;dynamic_templates&quot;.&quot;locale&quot; = ? AND &quot;dynamic_templates&quot;.&quot;format&quot; IN (?, ?) AND &quot;dynamic_templates&quot;.&quot;handler&quot; IN (?, ?, ?, ?, ?, ?) AND &quot;dynamic_templates&quot;.&quot;partial&quot; = ?  [[&quot;path&quot;, &quot;layouts/application&quot;], [&quot;locale&quot;, &quot;en&quot;], [&quot;format&quot;, &quot;html&quot;], [&quot;format&quot;, &quot;html&quot;], [&quot;handler&quot;, &quot;raw&quot;], [&quot;handler&quot;, &quot;erb&quot;], [&quot;handler&quot;, &quot;html&quot;], [&quot;handler&quot;, &quot;builder&quot;], [&quot;handler&quot;, &quot;ruby&quot;], [&quot;handler&quot;, &quot;jbuilder&quot;], [&quot;partial&quot;, 0]]<br>  ↳ app/models/dynamic_template.rb:22:in `map</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/689/1*VyqyUsIPUIdog7mvW5vE6w.png" /><figcaption>/<strong>posts</strong> Should look like this — an ugly CRUD app</figcaption></figure><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2F26DOoDwdNGKAg6UKI%2Ftwitter%2Fiframe&amp;display_name=Giphy&amp;url=https%3A%2F%2Fmedia.giphy.com%2Fmedia%2F26DOoDwdNGKAg6UKI%2Fgiphy.gif%3Fcid%3D790b7611a8j1gsnf576j57hmcz1txpixaepluqqxg0c5pbma%26ep%3Dv1_gifs_search%26rid%3Dgiphy.gif%26ct%3Dg&amp;image=https%3A%2F%2Fmedia2.giphy.com%2Fmedia%2Fv1.Y2lkPTc5MGI3NjExZTgwM2FmeWJkaDA0YjU2OWtvZGJtOWpjMmR5Ym92aG5nNmNhZHhlMiZlcD12MV9pbnRlcm5hbF9naWZfYnlfaWQmY3Q9Zw%2F26DOoDwdNGKAg6UKI%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="435" height="348" frameborder="0" scrolling="no"><a href="https://medium.com/media/fe24e4659fc861418e79ebe1a98195f5/href">https://medium.com/media/fe24e4659fc861418e79ebe1a98195f5/href</a></iframe><p>Ohh damn, you followed along this long “S” blog. Dedication!! <br>If you enjoyed this, <strong>follow</strong> and <strong>leave a 👏</strong> for the blog.</p><blockquote>Upcoming blog — Multi-Tenancy with subdomain integration with Rails7</blockquote><p>Also <strong>subscribe</strong> if you feel content is exciting and your learning from it :) —<br>It Gives me extra motivation to continue 😃, THANKS ALL!!</p><p>If you are a company that is building a similar product, let have a chat on <a href="https://x.com/RUTVIKCHANDLA">X</a></p><p><strong>[ Reference ]</strong><br><a href="https://github.com/RutvikChandla/dynamicrenderer">https://github.com/RutvikChandla/dynamicrenderer</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=459429ebbf0e" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Resolvers in Ruby and Rails]]></title>
            <link>https://medium.com/@rutvikchandla3/resolvers-in-ruby-and-rails-d3c9a38bbdba?source=rss-6a68ff3ffe76------2</link>
            <guid isPermaLink="false">https://medium.com/p/d3c9a38bbdba</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Rutvik Chandla]]></dc:creator>
            <pubDate>Tue, 02 Jul 2024 17:19:40 GMT</pubDate>
            <atom:updated>2024-07-02T17:19:40.912Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QFBxYlgiJ0-58pVky0DUIw.png" /></figure><h3>Resolvers</h3><p>Simply put, it is the class which is actually responsible for <strong>fetching the templates</strong> like <em>layout/application.html.erb</em> or<em> views/hello/index.html.erb</em></p><blockquote>Ever wondered how rails renders templates from the <em>app/views </em>?</blockquote><p>All view templates are <strong>actual files</strong> (.erb|.html etc), so there must be some fancy <strong><em>File.read()</em></strong> action going on inside rails codebase?</p><p>Uhmm YES —</p><pre># actionview-7.1.3.4/lib/action_view/template/sources/file.rb<br>module ActionView<br>  class Template<br>    module Sources<br>      class File<br>        def initialize(filename)<br>          @filename = filename<br>        end<br><br>        def to_s<br>          ::File.binread @filename<br>        end<br>      end<br>    end<br>  end<br>end</pre><h4>Resolver’s structure</h4><p>In case you want to build your own resolver, eg. Rendering templates from DB or S3 — understanding a structure is a must!</p><pre># actionview-7.1.3.4/lib/action_view/template/resolver.rb<br>class Resolver<br>    include ActiveSupport::Deprecation::DeprecatedConstantAccessor<br><br>    class PathParser # :nodoc:<br>      ...<br>    end<br><br>    cattr_accessor :caching, default: true<br><br>    class &lt;&lt; self<br>      alias :caching? :caching<br>    end<br><br>    def clear_cache<br>    end<br><br>    # Normalizes the arguments and passes it on to find_templates.<br>    def find_all(name, prefix = nil, partial = false, details = {}, key = nil, locals = [])<br>      _find_all(name, prefix, partial, details, key, locals)<br>    end<br><br>    def built_templates # :nodoc:<br>      # Used for error pages<br>      []<br>    end<br><br>    def all_template_paths # :nodoc:<br>      # Not implemented by default<br>      []<br>    end<br><br>  private<br>    def _find_all(name, prefix, partial, details, key, locals)<br>      find_templates(name, prefix, partial, details, locals)<br>    end<br><br>    delegate :caching?, to: :class<br><br>    # This is what child classes implement. No defaults are needed<br>    # because Resolver guarantees that the arguments are present and<br>    # normalized.<br>    def find_templates(name, prefix, partial, details, locals = [])<br>      raise NotImplementedError, &quot;Subclasses must implement a find_templates(name, prefix, partial, details, locals = []) method&quot;<br>    end<br>  end</pre><p>Main function here to look is <strong>find_all() </strong>— this function is responsible to find all the possible templates and return them to caller function i.e <a href="https://github.com/rails/rails/blob/main/actionview/lib/action_view/path_set.rb#L40-L43">Path Set</a></p><p>ActionView::Resolver is just an abstract class, the main implementation you’ll find in <a href="https://github.com/rails/rails/blob/main/actionview/lib/action_view/template/resolver.rb#L91">FileSystemResolver</a></p><pre>class FileSystemResolver &lt; Resolver<br>....<br>    private<br>      def _find_all(name, prefix, partial, details, key, locals)<br>        requested_details = key || TemplateDetails::Requested.new(**details)<br>        cache = key ? @unbound_templates : Concurrent::Map.new<br><br>        unbound_templates =<br>          cache.compute_if_absent(TemplatePath.virtual(name, prefix, partial)) do<br>            path = TemplatePath.build(name, prefix, partial)<br>            unbound_templates_from_path(path)<br>          end<br><br>        filter_and_sort_by_details(unbound_templates, requested_details).map do |unbound_template|<br>          unbound_template.bind_locals(locals)<br>        end<br>      end<br>....<br>end</pre><p>Above code is a bit complex (you need to look at entire file) but one can see we are returning unbound_templates.</p><pre> def build_unbound_template(template)<br>        parsed = @path_parser.parse(template.from(@path.size + 1))<br>        details = parsed.details<br>        source = source_for_template(template)<br><br>        UnboundTemplate.new(<br>          source,<br>          template,<br>          details: details,<br>          virtual_path: parsed.path.virtual,<br>        )<br>end</pre><p>For now you can assume Unbound templates are object on which .render method will be called to render raw string file content to HTML</p><p>The <em>source_for_template</em> is just <strong>File.binread</strong> using path.</p><p><strong>In upcoming blog I’ll be covering —</strong></p><blockquote>Rendering custom views from S3 or DB (SQL or NoSQL), there we will be using custom resolver.</blockquote><p>Follow so you don’t miss it :)</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fgiphy.com%2Fembed%2FAbOZR8G922HtmsfNlv%2Fvideo&amp;display_name=GIPHY&amp;url=https%3A%2F%2Fgiphy.com%2Fclips%2FLydia-Getachew-nike-just-do-it-shia-AbOZR8G922HtmsfNlv&amp;image=https%3A%2F%2Fmedia0.giphy.com%2Fmedia%2FAbOZR8G922HtmsfNlv%2Fgiphy.gif&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=giphy" width="480" height="270" frameborder="0" scrolling="no"><a href="https://medium.com/media/af932451b32be38dc0fabb5911f585fb/href">https://medium.com/media/af932451b32be38dc0fabb5911f585fb/href</a></iframe><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=d3c9a38bbdba" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Render custom format files in Rails]]></title>
            <link>https://medium.com/@rutvikchandla3/render-custom-format-files-in-rails-690435220993?source=rss-6a68ff3ffe76------2</link>
            <guid isPermaLink="false">https://medium.com/p/690435220993</guid>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <dc:creator><![CDATA[Rutvik Chandla]]></dc:creator>
            <pubDate>Wed, 19 Jun 2024 17:06:47 GMT</pubDate>
            <atom:updated>2024-06-19T17:06:47.135Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*h2_F2bILp8sdGrZP" /></figure><h3>Introduction</h3><p>Rails knows how to render [:json, :js, :xml] types of formats, but what if you want to render a format like pdf?</p><p>I know I know, there are lots of gems (<a href="https://rubygems.org/gems/wicked_pdf/versions/2.1.0?locale=en">wicked_pdf</a>) to do this, but as a tinkerer I wanted to see how by rails internally do this and can I leverage any Rails API to achieve this.</p><p>We already know that we can use render.json — searching in rails code base got this code —</p><pre>    <br># actionpack-7.1.3/lib/action_controller/metal/renderers.rb<br><br>  add :json do |json, options|<br>      json = json.to_json(options) unless json.kind_of?(String)<br><br>      if options[:callback].present?<br>        if media_type.nil? || media_type == Mime[:json]<br>          self.content_type = Mime[:js]<br>        end<br><br>        &quot;/**/#{options[:callback]}(#{json})&quot;<br>      else<br>        self.content_type = Mime[:json] if media_type.nil?<br>        json<br>      end<br>    end</pre><pre># sample action to renderd data as json<br><br>def index<br>  data = Posts.all<br>  render json: posts.to_json<br>end</pre><h3>Solution</h3><p>So, we just need to tell rails similar to json that how to render PDFs. As :add is already defined in ActionController::Renderers, we should use the API to inject our code block. Can use new initializers file to load it before anything else.</p><pre># config/initializers/pdf_renderers.rb<br><br>require &quot;prawn&quot;<br><br>ActionController::Renderers.add :pdf do |filename, options|<br>  pdf = Prawn::Document.new<br>  pdf.text render_to_string(options)<br>  send_data(pdf.render, filename: &quot;#{filename}.pdf&quot;, disposition: &quot;attachment&quot;)<br>end</pre><p><strong>:add</strong> method takes, format and a block to run. <br><strong>send_data</strong> is the function defined in rails to send data.. ah self explanatory!</p><p>What will <strong>render_to_string(options)</strong> will do? <br><strong>options</strong> is basically a hash that tells which “view” file to render<br><strong>render_to_string</strong> will fetch the data from the view file and convert to string</p><pre>&gt; puts options<br>=&gt; {:prefixes=&gt;[&quot;home&quot;, &quot;application&quot;], :template=&gt;&quot;index&quot;, :layout=&gt;#&lt;Proc:0x000000011374c048 /Users/ritvik/.rvm/gems/ruby-3.2.0/gems/actionview-7.1.3.4/lib/action_view/layouts.rb:395&gt;}</pre><p>That’s it? YES.</p><pre>class HomeController &lt; ApplicationController<br>  def index<br>    respond_to do |format|<br>      format.pdf { render pdf: &quot;contents&quot;}<br>      format.html<br>    end<br>  end<br>end</pre><pre># dummy/app/views/home/index.pdf.erb<br><br>This template is rendered with Prawn.</pre><p>Now if you rails server and got to “<a href="http://127.0.0.1:3000/home">http://127.0.0.1:3000/home</a>.pdf”, A PDF will be downloaded!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8q4A0WgJ0uwHjQ03nRIQNQ.png" /></figure><p>Code ref:<br><a href="https://github.com/RutvikChandla/pdf_renderer/commit/46e582e2f068fb2361f7fe3f44a1dcbb585f3d03">https://github.com/RutvikChandla/pdf_renderer/commit/46e582e2f068fb2361f7fe3f44a1dcbb585f3d03</a></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=690435220993" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>