<?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 Sushi Chanrai on Medium]]></title>
        <description><![CDATA[Stories by Sushi Chanrai on Medium]]></description>
        <link>https://medium.com/@tominagirl?source=rss-8fb03435e9cc------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/1*lcydAQuM1gmvmfuNUag_Lw.jpeg</url>
            <title>Stories by Sushi Chanrai on Medium</title>
            <link>https://medium.com/@tominagirl?source=rss-8fb03435e9cc------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Sat, 05 Dec 2026 15:36:40 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@tominagirl/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[PMs should own model evaluation]]></title>
            <link>https://ai.plainenglish.io/pms-should-own-model-evaluation-b77d39252f61?source=rss-8fb03435e9cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/b77d39252f61</guid>
            <category><![CDATA[ai-product-management]]></category>
            <category><![CDATA[embedding]]></category>
            <category><![CDATA[retrieval-augmented-gen]]></category>
            <category><![CDATA[healthtech]]></category>
            <category><![CDATA[product-management]]></category>
            <dc:creator><![CDATA[Sushi Chanrai]]></dc:creator>
            <pubDate>Sun, 02 Aug 2026 21:53:17 GMT</pubDate>
            <atom:updated>2026-08-02T21:53:17.679Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*hxbAhQqyIHjSeAzf1HaHtQ.png" /></figure><h3>PMs Should Own Embedding Model Evaluation — Not Just Model Selection</h3><p><em>There’s something seductive about a benchmark leaderboard. It arrives with the air of having done the hard work for you — here are the models, ranked by people who know more than you do, in the domain you care about, so you can skip straight to the implementation.</em></p><p><em>I was building Long COVID Compass — a RAG system that enables people with Long COVID to ask questions about their condition, and get grounded, community-sourced answers drawn from a Reddit dataset of 184,000 chunks. When it came time to pick an embedding model, I pulled up Hugging Face’s MTEB leaderboard — the Massive Text Embedding Benchmark, which ranks embedding models across retrieval, classification, and similarity tasks</em> —<em> filtered by Medical Retrieval, and found Qwen3-Embedding-4B sitting at 92.92 which represented the highest score in my shortlist. The obvious choice seemed to already be made, but I ran a proper evaluation anyway — what came back surprised me.</em></p><p><em>Here’s what that process taught me, and why I think model evaluation is something PMs need to own, not just sign off on.</em></p><h3>Setting up the test</h3><p>I wrote the queries first, because the queries are what define what “relevant” actually means and you can’t build a corpus or pick a model without knowing what you’re evaluating against. Twenty golden queries across seven categories — symptom, treatment, timeline, prevalence, emotional, benefits, and meta — written by me, not pulled from any existing benchmark. I wrote them across deliberately different registers, from the clinically phrased questions a researcher might run to the kind of broken, emotionally raw phrasing a patient in the middle of a flare might actually type into a search box at 11pm. The queries are where the evaluation either reflects your users or doesn’t, and once you’ve spent any real time in a chronic illness community, the way patients write becomes impossible to un-see.</p><p>The corpus came next. Long COVID Compass runs on informal Reddit health text, which sits at the intersection of medical terminology and conversational register — neither Medical Retrieval nor Social/Blog Retrieval performance alone was a sufficient signal for how a model would actually perform here. Both had to be strong.</p><p>And finally the shortlist of models, three of which I’d picked off the MTEB leaderboard for their strong Medical Retrieval or Social/Blog Retrieval scores.</p><h3>The query that changed how I think about this</h3><p>Query 19 in my golden set was: <em>“LC awareness. Doctor and family don’t believe me =( ”</em></p><p>I wrote it that way deliberately, because it’s ambiguous on almost every dimension — and that ambiguity is the point. “<em>LC</em>” is a bare abbreviation that, without domain familiarity, you’d have no way of decoding, and even with that knowledge the embedding model sees two letters rather than the concept behind them. “<em>Doctor and family don’t believe me</em>” carries at least three distinct intents at once for the patient asking:</p><ul><li>Resources they can bring to a family member or doctor who doesn’t believe them</li><li>Validation from a community that already knows what medical dismissal feels like</li><li>Language for an experience they may not have words for yet</li></ul><p>The sad face at the end signals emotional distress rather than a clinical research question, which shifts the retrieval need again. A single query, and the system has to decide what it’s actually being asked.</p><p>Without time in the Long COVID community, the natural instinct is to clean the query up before testing — “<em>Long COVID awareness and medical gaslighting,</em>” say, fully formed and clinically phrased, which is a perfectly reasonable thing to write. However, patients don’t write in that way, and the gap between those two versions is exactly where the failure hides.</p><h3>What the data showed</h3><p>To understand what happened on q19, it helps to look at how the test was actually set up. Each model candidate was on the shortlist for a specific reason:</p><ul><li><strong>Qwen3-Embedding-0.6B</strong> — the best ratio of retrieval quality to model size I could find, with strong Medical Retrieval at 90.52, decent Social/Blog at 70.97, and small enough to run without GPU infrastructure.</li><li><strong>Jasper-Token-Compression-600M</strong> — the strongest cross-domain performer at sub-1B scale, with the highest Social/Blog Retrieval score of any model in its size class while keeping Medical performance competitive.</li><li><strong>Qwen3-Embedding-4B</strong> — included to test whether three billion more parameters bought meaningfully better retrieval. On Medical Retrieval it sat at 92.92, the highest score in the shortlist.</li><li><strong>Voyage-4-Large</strong> — the API option, the simplest pipeline if retrieval quality held up. It hadn’t been benchmarked on MTEB at the time of testing.</li></ul><p>With the queries written, I built an eval corpus of 2,000 chunks: 432 positives drawn from the actual Long COVID Reddit dataset that I’d manually verified as genuinely relevant to at least one query type, and 1,568 distractors — chunks from the same dataset that are plausibly related to the topic but not genuinely useful for any specific query, included to test whether each model could separate signal from noise rather than just retrieving anything vaguely Long COVID-adjacent.</p><p>For metrics I used <strong>NDCG@10</strong> (Normalised Discounted Cumulative Gain, which rewards models that rank the most relevant chunks highest) and <strong>MRR@10</strong> (Mean Reciprocal Rank, which tells you how far down the list you scroll before hitting the first relevant result). Scoring was done by an LLM-as-judge —<strong> Gemini 2.5 Flash Lite</strong> — which I chose for speed, cost, and the fact that its output is concise rather than verbose, which matters when you’re scoring 2,000 chunk-query pairs and need consistent, readable verdicts. Across the scoring runs, the verdicts read accurate to me.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*fQYHYMfQioqIXzNg2RiPLQ.png" /></figure><p><strong>Voyage-4-Large </strong>won across every metric — highest proportion of highly relevant chunks, fewest irrelevant results, and the first relevant result at the top of the list on every single query.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8UVq_w-BoMc3aSQ5hWE_YQ.png" /></figure><p><strong>MTEB</strong> tests what it’s designed to test. The problem is that what it tests often doesn’t match what your users actually do. Leaderboards rank models against clean, researcher-written queries. Your users don’t write like researchers, and in a domain like Long COVID, that gap is wider than you’d expect.</p><p>Coming back to q19: even <strong>Voyage-4-Large</strong>, the strongest overall performer, scored 0.9188 on it — its single lowest score, against a mean of 0.9903 across all twenty — and the root cause was the abbreviation producing a weaker embedding signal. The important thing is that the failure showed up in evaluation rather than in production, and it led directly to an architectural fix: a query rewriting step that expands <em>“LC → Long COVID”</em> before retrieval. That’s a decision shaped entirely by the evaluation catching something that clean test queries would never have surfaced.</p><h3>Why this is a PM’s job</h3><p>The 20 queries I wrote required judgment calls that don’t live anywhere in an engineering brief — knowing that patients write “<em>LC</em>” not “<em>Long COVID</em>,” that queries arrive emotionally raw rather than clinically neutral, that emotional and benefits queries (“<em>will I get better,</em>” “<em>can I claim disability</em>”) matter as much to this population as symptom and treatment queries, and that what good retrieval looks like shifts depending on whether the person asking is in crisis or calmly doing research. This is user knowledge, and it comes from time spent in the community — reading the threads, absorbing the vocabulary of chronic illness, internalising what people are actually trying to find when they’re exhausted and being dismissed by doctors.</p><p>A 2025 <a href="https://www.jmir.org/2025/1/e84120">JMIR systematic review</a> of 39 medical AI benchmarks found that LLMs score 84–90% on knowledge-based exams but drop to 45–69% in practice-based clinical scenarios — knowledge that doesn’t transfer to the messiness of real clinical situations. The same gap shows up at the retrieval layer when you pick a model from a leaderboard without testing it against the queries your users actually write.</p><p>PMs are the people most likely to have the user proximity to write those queries well. Engineers can absolutely do it; PMs are usually closer to the user knowledge that makes the queries good.</p><h3>Before your team picks a model</h3><p>Write 20 queries the way your users actually write them — not the polished version, but the actual string they’d type at the end of a long day when they’re frustrated and searching for something that might help. Run them against your shortlisted models on a representative corpus, spend time on the failure cases, and when you find one, ask why. The answer will usually tell you something about your users you hadn’t fully articulated before.</p><p><em>Long COVID Compass is live — you can try it at </em><a href="http://rag-longcovid-reddit-navigator-fron.vercel.app/"><em>rag-longcovid-reddit-navigator-fron.vercel.app</em></a><em>. If you’re a founder or builder working on a RAG product and want to swap war stories, I’d genuinely love to hear from you.</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=b77d39252f61" width="1" height="1" alt=""><hr><p><a href="https://ai.plainenglish.io/pms-should-own-model-evaluation-b77d39252f61">PMs should own model evaluation</a> was originally published in <a href="https://ai.plainenglish.io/">Artificial Intelligence in Plain English</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[How I Stopped My AI Coding Partner From Going Off the Rails]]></title>
            <link>https://medium.com/@tominagirl/how-i-stopped-my-ai-coding-partner-from-going-off-the-rails-6526de6bffbc?source=rss-8fb03435e9cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/6526de6bffbc</guid>
            <category><![CDATA[developer-experience]]></category>
            <category><![CDATA[ai-tools]]></category>
            <category><![CDATA[product-management]]></category>
            <category><![CDATA[cursor-ai]]></category>
            <category><![CDATA[vibe-coding]]></category>
            <dc:creator><![CDATA[Sushi Chanrai]]></dc:creator>
            <pubDate>Tue, 07 Oct 2025 03:06:32 GMT</pubDate>
            <atom:updated>2025-10-08T22:35:03.496Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc-nd/4.0/</cc:license>
            <content:encoded><![CDATA[<h3><em>Taming the Chaos: What “Vibe Coding” Taught Me About AI and Trust</em></h3><p><em>Working with AI code editors can feel like pairing with your most chaotically creative teammate— brilliant but unpredictable. Here’s how I turned that chaos into collaboration with a few simple rules, and what it taught me about trust, boundaries, and product thinking</em></p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*KStCXbyAcK4K2QhbZqPVbA.png" /></figure><p>Vibe coding without rules feels like working with your most <em>chaotically creative </em>teammate — full of brilliant ideas, zero filter, and constantly starting three new ones before finishing one.</p><p>That’s what it was like when I first started using AI code editors like <a href="https://cursor.com/">Cursor</a> to build prototypes and custom tools for clients.</p><p>The model would:</p><ul><li>Suggest full libraries for problems that needed 15 lines of vanilla JS.</li><li>Rewrite working code because it “thought” it could do better.</li><li>Fixate on a minor bug and ignore the actual problem.</li></ul><p>It wasn’t “wrong” so much as <strong>context-blind</strong> — reacting to patterns it recognized rather than the problem in front of it.</p><p>That’s when I realized: vibe coding doesn’t just need <em>prompts</em> — it needs <em>rules.</em></p><h3>🧨 Before the Rules</h3><p>When I first started working with AI code editors, it wasn’t pretty. I’d let AI take the wheel and then spend hours cleaning up after it.</p><p>A few offenses stand out from those early days:</p><h4><strong>Complex Solution Over Simple</strong></h4><p>The model suggested a full ReactMarkdown library for three hyperlinks.</p><p>I needed a short regex. Result: 50 KB of wasted bundle size avoided.</p><pre>// What AI suggested (COMPLEX):<br>import ReactMarkdown from &#39;react-markdown&#39;<br><br>const MarkdownContent = ({ content }: { content: string }) =&gt; (<br>  &lt;div className=&quot;prose prose-sm max-w-none text-muted-foreground&quot;&gt;<br>    &lt;ReactMarkdown<br>      components={{<br>        a: ({ node, ...props }) =&gt; (<br>          &lt;a <br>            {...props} <br>            target=&quot;_blank&quot; <br>            rel=&quot;noopener noreferrer&quot;<br>            className=&quot;text-blue-600 hover:underline&quot;<br>          /&gt;<br>        ),<br>        ul: ({ node, ...props }) =&gt; (<br>          &lt;ul className=&quot;list-disc pl-5 space-y-1&quot; {...props} /&gt;<br>        ),<br>        p: ({ node, ...props }) =&gt; (<br>          &lt;p className=&quot;mb-4 last:mb-0&quot; {...props} /&gt;<br>        )<br>      }}<br>    &gt;<br>      {content}<br>    &lt;/ReactMarkdown&gt;<br>  &lt;/div&gt;<br>)<br><br>// What was actually needed (SIMPLE):<br>const renderSourceWithLinks = (source: string) =&gt; {<br>  const linkRegex = /\[([^\]]+)\]\(([^)]+)\)/g;<br>  // 15 lines of vanilla JS<br>}</pre><h4>Breaking Conventions</h4><p>The AI renamed working tab values without checking, breaking navigation.</p><p>My Working Tab Structure:</p><pre>// components/brand-profile-panel.tsx - Lines 20-40 (existing)<br>&lt;TabsList className=&quot;mb-4 bg-edge border border-gray-200 p-1 rounded-lg&quot;&gt;<br>  &lt;TabsTrigger<br>    value=&quot;overview&quot;<br>    className=&quot;data-[state=active]:bg-white data-[state=active]:text-black...&quot;<br>  &gt;<br>    Overview<br>  &lt;/TabsTrigger&gt;<br>  &lt;TabsTrigger<br>    value=&quot;report&quot;  //  EXISTING VALUE<br>    className=&quot;data-[state=active]:bg-white data-[state=active]:text-black...&quot;<br>  &gt;<br>    Full Report<br>  &lt;/TabsTrigger&gt;<br>&lt;/TabsList&gt;<br><br>&lt;TabsContent value=&quot;report&quot; className=&quot;space-y-4&quot;&gt;  // WORKING</pre><p>What the AI Suggested Without Checking:</p><pre>// Cursor suggestion (WOULD BREAK MY APP):<br>&lt;TabsTrigger value=&quot;full-report&quot;&gt;Full Report&lt;/TabsTrigger&gt;  // NEW VALUE<br>&lt;TabsContent value=&quot;full-report&quot;&gt;  // DIFFERENT VALUE = BROKEN TABS</pre><h4>Ignoring Existing Data Patterns</h4><p>It restructured my schema even though the UI expected a simple .content property.</p><p>The UI Expected This Structure:</p><pre><br>// components/brand-profile-panel.tsx - Lines 143-156 (existing)<br>{company.detailedAnalysis?.marketingActivity &amp;&amp; (<br>  &lt;AccordionItem value=&quot;marketing-activity&quot;&gt;<br>    &lt;AccordionTrigger&gt;Marketing Activity&lt;/AccordionTrigger&gt;<br>    &lt;AccordionContent&gt;<br>      &lt;p className=&quot;text-sm text-muted-foreground&quot;&gt;<br>        {company.detailedAnalysis.marketingActivity.content}  // SIMPLE .content<br>      &lt;/p&gt;<br>    &lt;/AccordionContent&gt;<br>  &lt;/AccordionItem&gt;<br>)}</pre><p>But the AI Implemented Complex Schema Mapping:</p><pre>// Cursor&#39;s over-engineered suggestion:<br>marketingActivity: {<br>  globalMarketing: formattedMarketing.marketingActivity?.content,<br>  regionalMarketing: formattedMarketing.marketingActivity?.content<br>}<br><br>// When I already had simple working structure expecting:<br>marketingActivity: { content: &quot;...&quot; }</pre><p>Each one was a <strong>trust misfire</strong> — Cursor’s underlying model defaulted to its own learned patterns instead of my project’s context.</p><p>That’s when it clicked: vibe coding doesn’t just need prompts — it needs <strong>principles</strong></p><h3>🧭 The Rules of Engagement</h3><p>After a few chaotic sprints, I built myself a framework — seven simple rules that turned the experience from unpredictable to productive:</p><p>1️⃣ <strong>Simplicity First</strong> — start lean, only add complexity when necessary.</p><p>2️⃣ <strong>Dependency Management</strong> — no extra packages unless absolutely essential.</p><p>3️⃣ <strong>Present Options</strong> — ask for 2–3 possible approaches, not one over-confident answer.</p><p>4️⃣ <strong>Justify Complexity</strong> — if it can’t explain <em>why</em>, it doesn’t belong.</p><p>5️⃣ <strong>Code Exploration First</strong> — check what already exists before rewriting.</p><p>6️⃣ <strong>Ship in steps — s</strong>mall, testable chunks beat grand rewrites</p><p>7️⃣ <strong>Question Complexity</strong> — “Is there a simpler way?” should be the default prompt.</p><p>Following these rules didn’t make the model perfect — it just stopped me from spiraling.</p><p>When I began re-anchoring Cursor with them at the start of every major task, the chaos began to settle. The system didn’t suddenly become smarter; It just steadied up once I took the wheel. That process eventually evolved into something more structured — a system I could reuse and refine over time.</p><h3>⚙️ Supercharging My Rules with Cursor Directory</h3><p>Eventually, I discovered the <a href="https://cursor.com/docs/context/rules#cursorrules"><strong>Cursor Rules Directory</strong></a> — library where devs share and generate rule sets. It’s a goldmine of guardrails: early returns, clear naming, lightweight solutions — the kind of stuff that keeps code clean and AI grounded.</p><p>Rather than embedding them in Cursor’s global settings, I made a dedicated <strong>.cursorrules</strong> file in the project root — a single source of truth I could load before major tasks to re-anchor Cursor in three principles: simplicity, clarity, and reasoning before rewriting.</p><p>This approach (as explained nicely in <a href="https://www.youtube.com/watch?v=Vy7dJKv1EpA">this video</a>) meant I wasn’t fighting Cursor’s defaults anymore. I could pull that file into context whenever I started something big, and it instantly reset the tone of collaboration.</p><p>Cursor, by design, tends to <strong>pattern-match on previous conversations</strong> instead of systematically applying rules. Reloading that file gave the model a clean slate — a way to re-anchor itself before those patterns took over.</p><p>It wasn’t automation; it was an intentional reset — a quick gut check that kept me honest.</p><h3>🧠 The Psychology of Trust</h3><p>Once I stepped back, I realized what I was really managing wasn’t code — it was <strong>trust.</strong></p><p>Recent research mirrors what I’ve seen firsthand. Developers (me included) will let AI help scaffold things, but rarely let it near the critical path. We trust it more when it explains <strong><em>why</em></strong>, not just <strong><em>what</em></strong>. And we trust it most when we can challenge it — when we stay in control.</p><p>Studies like <a href="https://www.sciencedirect.com/science/article/abs/pii/S0950584924002155"><em>Using AI-Based Coding Assistants in Practice</em> (2025)</a>, <a href="https://research.google/pubs/identifying-the-factors-that-influence-trust-in-ai-code-completion/"><em>Identifying the Factors That Influence Trust in AI Code Completion</em> (Google, 2024)</a>, and <a href="https://dl.acm.org/doi/10.1145/3630106.3658984"><em>Investigating and Designing for Trust in AI-Powered Code Generation Tools</em> (Wang et al., 2023)</a> all point in the same direction — <strong>trust is earned through transparency, explanation, and control, not accuracy alone.</strong></p><p>These insights echo what I’ve learned through practice: the rules and prompts I use aren’t just about structure — they’re about turning blind acceptance into a dialogue.</p><p>Trust, I’ve learned, isn’t binary. You’re constantly <strong>calibrating</strong> it — deciding when to follow, when to override, and when to make the AI justify its choices.</p><h3>🔍 What I Missed at First</h3><p>The real problem wasn’t technical — it was <strong>attention drift.</strong> Both the AI and I were solving the wrong thing first.</p><p>This was pattern-matching bias at play — the model repeated a previous context rather than assessing the real problem.</p><p>That’s why <strong>Rule #5 — Explore the Codebase First</strong> — exists.</p><p>It forces both me and the system to slow down, verify assumptions, and focus on impact, not activity.</p><h3>🧭 Keeping AI on Track</h3><p>Even with a solid framework, AI drifts. It over-engineers, skips context, or gets clever when all you need is clean code.</p><p>Every time it wandered, I’d call it out: “Is this the simplest explanation?” Then I’d make it reference the rule it had just broken. Researchers call that <em>trust calibration</em>. I just call it being the senior in the room — reviewing work, keeping it honest.</p><p>That rhythm — asking, challenging, resetting — became the real loop.</p><p>Not automation, just awareness.</p><p>Over time, it reshaped how I worked: faster, cleaner, more intentional — learning to work <em>with</em> AI, not around it.</p><p>Vibe coding with rules turns chaos into flow.</p><p>Without them? It’s just your most chaotically creative friend, five espressos deep, writing slam poetry straight into your codebase.</p><p>✨ <em>If you’ve been vibe coding lately — how do you keep it on the rails? Rules, prompts, or pure instinct?</em></p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=6526de6bffbc" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Faking it while you build it]]></title>
            <link>https://medium.com/@tominagirl/faking-it-while-you-build-it-5378e97d2bf0?source=rss-8fb03435e9cc------2</link>
            <guid isPermaLink="false">https://medium.com/p/5378e97d2bf0</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[faker-gem]]></category>
            <category><![CDATA[coding]]></category>
            <category><![CDATA[web-development]]></category>
            <category><![CDATA[ruby-on-rails-development]]></category>
            <dc:creator><![CDATA[Sushi Chanrai]]></dc:creator>
            <pubDate>Mon, 31 Aug 2020 21:05:26 GMT</pubDate>
            <atom:updated>2020-09-01T16:25:00.726Z</atom:updated>
            <cc:license>https://creativecommons.org/licenses/by-nc/4.0/</cc:license>
            <content:encoded><![CDATA[<h4>Generating a robust test data foundation in Rails applications with Faker</h4><figure><img alt="Fact Fake Game Dice" src="https://cdn-images-1.medium.com/max/768/1*EWa43tJVDkH0ZSpmfwKq6Q.png" /></figure><p><a href="https://github.com/faker-ruby/faker"><strong>Faker</strong></a> is a tremendously useful Ruby library that generates random data on the fly to populate your database with real-looking data. The prospect of getting real-looking test data instantly, and having a database populated with more than one or two records is clearly an attractive and time-saving proposition when building and testing your Ruby or ROR apps.</p><p>When I first learned about Faker, I was building a simple, no-frills forum web application — a perfect opportunity to leverage it and speed up the development process. I gleefully accepted a dinner invitation for that evening with the plan to have my database seeded by then. In reality, it took me a whole day to get the data looking right!</p><p>Initially, I referenced the articles by <a href="https://medium.com/@sotek222/seed-your-database-with-fakes-using-faker-5ba5dccda44f"><strong>Matthew Masiello</strong></a> and <a href="https://medium.com/@yassimortensen/using-faker-to-seed-your-rails-database-cbfb0960d573"><strong>Yassi Moretenson</strong></a> to help me with the installation and initial configuration. The README <a href="https://github.com/faker-ruby/faker"><strong>documentation</strong></a> is concise and covers most areas at a high level, but the real learning came through trial and error.</p><h4>A Quick Example</h4><p>Let’s say we want to create a user in our Rails database. We want this user to have a <em>name</em>, <em>email </em>and<em> password.</em></p><p>In Ruby, (once we have correctly set up our models and run our migrations on our Rails database) we would do this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/23dcf03462ff94e14d1d6368a4dab39c/href">https://medium.com/media/23dcf03462ff94e14d1d6368a4dab39c/href</a></iframe><p>Simple enough right? But what if we need to create an additional ten users? Clearly there are too few hours in the day to repeat the above nine more times!</p><p>Armed with Faker and the knowledge of how to leverage your seeds.rbfile to <a href="https://www.chrisjmendez.com/2016/12/18/populating-your-database-in-rails-using-seeds/"><strong>seed your database</strong></a>, all we would do is this:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a61b8d06fcafe868eea2d9f73648c582/href">https://medium.com/media/a61b8d06fcafe868eea2d9f73648c582/href</a></iframe><p>After running rake db:seed, 10 user objects are instantly populated in our database with usernames, emails and passwords of a minimum length.</p><h4>Layering the data foundation</h4><p>Whilst it may be tempting to mass-populate from the get-go given the simplicity of the library, I would strongly recommend to seed in increments. In this way, you can evaluate if the criteria/specifiers that you have set up for each generator and model work for your application.</p><p>Once you have run the rake db:seed command (as many times as desired) and you have populated the database according to your requirements for that specific model, <strong>it’s important to remember to delete the Faker method call in the seed file that pertains to that model</strong>. The reason being that every time you run the rake db:seed command, you will execute all the methods/commands in your seed file.</p><p>For instance, if you run the following block of code with the rake db:seed call once, it will generate 3 distinct user records in your database with name, email, and password attributes set.</p><pre>3.times do<br>    User.create(<br>        name: Faker::Name.username,<br>        email: Faker::Internet.email,<br>        password: Faker::Internet.password<br>)<br>end</pre><p>If nothing changes in the seed file and you run the rake db:seed command again because you have another model you are trying to populate as follows:</p><pre>3.times do<br>    Quote.create(<br>        description: Faker::Quote.yoda<br>)<br>end</pre><p>you would have 6 users records seeded in the database, but only 3 quote records.</p><p>Staggering the seeding is also useful if you’re planning to build any time-based queries or methods in your application, your records are not populated all at the same time. In this way, you won’t have to drill down to milliseconds to see the difference between the records when writing and testing chronological sorting, filtering or ordering functions.</p><h4>Respect your own business rules</h4><p>It’s important to bear in mind that Faker generates data at random every time you call a method on its library of data. This data is not unique by default unless you prefix your method call with unique as follows:</p><pre>Faker::Name.unique.name # This will return a unique name every time it is called</pre><p>However, Faker cannot compare previous seeded passes, this means that whilst all values in the current pass are unique, you have no guarantee that the next pass will not replicate some of the same values as the previous pass. You can prevent against any erroneous data being created in the database by having the right validations in place on your models.</p><p><strong>Circumstances may also arise when your business and data rules get compromised</strong>. Unfortunately, Faker does not provide for customization of the generator, but Ruby validations can minimize error.</p><p>For example, in the environment of my Vanilla Forum App, a user cannot create more than one upvote on a single post. This meant that when I initially seeded the data (with no validations), <strong>it created duplicate upvotes from the same user on posts. </strong>I implemented a validation on the model after the fact to address this, but had it been in place before it would simply not allow me to run rake db:seed. Therefore, I had to make a trade-off for each attribute/model on whether to use Faker to generate the data quickly and go back and adjust versus creating each record manually.</p><p>Another pitfall I encountered whilst generating my seed data, was in relation to topic and post data. In my business logic, I wanted to make it mandatory to associate a post with a topic when a topic is created. In the interests of expediting the seed data creation process, I generated a bunch of topics in the database with no associated posts and made a mental note to encapsulate the required logic in the validations for the topic model later down the line. What a rookie mistake!</p><p>Whilst this oversight seemed innocuous in the early stages of the build, it came back to haunt me in the final stages of the build, as I spent an entire day trying to isolate a bug on my threads(topics) homepage.</p><p>The bug appeared when iterating around a topic’s oldest post and its associated user data:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0d682002715a4d407c9a426e5a99d597/href">https://medium.com/media/0d682002715a4d407c9a426e5a99d597/href</a></iframe><p>Iterating and exposing the values of the topic’s associated user’s username attribute did not pose an issue when testing in an IRB console within the scope of a pry. However, when running the code, the error messageNoMethodError: undefined method ‘user&#39; for nil:NilClass kept appearing in the view on the following line of code:</p><pre>&lt;%= posty.user.username %&gt;</pre><p>I eventually realized that error was being thrown at various points in the loop where the topic (thread) had no associated posts. At these points, there was indeed nothing encapsulated in posty, because during the seed generation process I had no way to ‘teach’ Faker my business rules.</p><p>I solved for this by usingtry and refactored the rest of my methods in the data loop, so that the threads/topics with no associated post data could be displayed error-free:</p><pre>&lt;%= posty.try(:user).try(:username) %&gt;</pre><figure><img alt="" src="https://cdn-images-1.medium.com/max/856/1*N4FmONhB7zpNTGdVyA_2dw.png" /></figure><h4>Conclusion</h4><p>Overall, I believe that you can leverage Faker to save development time if you use it carefully, paying close attention to your business logic and the impacts on your data rules.</p><p>To catch potential errors that could compromise your business rules or prevent bugs, I would recommend having a good database visualizer tool to view and edit database records when you are creating data with Faker. I used <a href="https://sqlitebrowser.org//"><strong>DB Browser for SQLite</strong></a><strong> </strong>which allows you to sort columns in tables easily and view all your data in tables at a glance, a feature that proved to be invaluable for me in identifying duplicates in the generated data.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*PYXgAln7xwf-g7i1SkZ30A.png" /></figure><p>You can also check out the incredibly helpful user forums on <a href="https://groups.google.com/g/ruby-faker?pli=1">Google Groups</a> or <a href="https://discord.gg/RMumTwB">Dischord</a> for tips and support on getting the most out of this handy library.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5378e97d2bf0" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>