<?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 August Bautra on Medium]]></title>
        <description><![CDATA[Stories by August Bautra on Medium]]></description>
        <link>https://medium.com/@augustsbautra?source=rss-47874e2a695f------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/0*P0Io59cyI8DmSQCs.png</url>
            <title>Stories by August Bautra on Medium</title>
            <link>https://medium.com/@augustsbautra?source=rss-47874e2a695f------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Fri, 20 Nov 2026 13:38:03 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@augustsbautra/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[My Mind Was Changed About Keto]]></title>
            <link>https://medium.com/@augustsbautra/my-mind-was-changed-about-keto-cbe32d0096ab?source=rss-47874e2a695f------2</link>
            <guid isPermaLink="false">https://medium.com/p/cbe32d0096ab</guid>
            <category><![CDATA[diet]]></category>
            <category><![CDATA[keto]]></category>
            <category><![CDATA[health]]></category>
            <category><![CDATA[weight-loss]]></category>
            <dc:creator><![CDATA[August Bautra]]></dc:creator>
            <pubDate>Wed, 19 Aug 2026 18:06:04 GMT</pubDate>
            <atom:updated>2026-08-19T18:11:45.827Z</atom:updated>
            <content:encoded><![CDATA[<h4>High-protein diet is the only option for weight loss</h4><p>I’ve been an advocate for ketogenic diet for weight loss and health improvement for over a decade. Recently I learned something that has changed my mind.</p><p>To understand the shift, we have to talk about the language and terms we use when describing diets.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*06cDHPiGCz9MYbzJ1FebVA.png" /></figure><p>We use a wild, imprecise mix of macronutriet notation, actual foodstuff sources and supposed metabolic state markers. We have to do better…</p><p>As a start, we could clarify the <strong>macronutrient composition</strong> of the diet, in calories. Protein-Fat-Carbs. For example, this disambiguates a non-ketogenic pseudo-SAD “high-fat” diet of 30–40–30 macro split from a maintenance-ketogenic 15–80–5 diet.</p><blockquote>Marconutrient proportions of a diet are insufficient to determine the metabolic effect it will have.</blockquote><p>But this is not enough, we also need at least the daily <strong>calorie count</strong>.</p><p>Combining these two numbers lets us infer a third, perhaps the most important metric — predominant <strong>metabolic state</strong> + muscle maintenance likelihood. Inferring is bounded by two numbers — the ~50g maximum for carb intake to maintain ketosis, and the 2g/lean-ish body mass of protein.</p><p>Both protein and carb grams are obtained with &lt;daily calories&gt; / 4 * &lt;proportion&gt; e.g. For a “15–80–5 2500/d” daily carbs come out at 31.25g.</p><p>Let’s try some examples!</p><ol><li>15–80–5 2500/d = near-overfeeding nutritional ketosis</li><li>20–30-50 1900/d = “stagflation” fattening + low energy SAD fog</li><li>12–80–8 3000/d = 75g of daily carbs prevents ketosis, fattening</li><li>5–60–35 5000/d = sumo-wrestler tactical enfattening — enormous energy surplus with enough carbohydrate to make ketosis unlikely</li><li>83–(12)–5 1000/d = high-protein weight-loss ketosis</li></ol><p>Example 5 helps me illustrate my point. The macros look nothing like a ketogenic diet, but due to carb restriction, free fatty acid release and ketone production will follow, amounting to most of energy metabolism being run on endogenous fat stores.</p><p>Also notice the brackets on the 12% of fat calories. That is the macronutrient that can happily grow to help deal with hunger and as we approach maintenance weight.</p><p>Now let’s try to design a weight loss diet based on these principles. The invariants are that we need at least 2g/kg of protein in it, and some essential fatty acids (but these will naturally occur in meat and omega-3 supplementation will not bear on macros). For an 80kg man that would come to 160g = 640kcal right there. Throw in 12g of natural fat from 100g of lean protein from meat (using whey powder or a similar protein source will not have this!), that’s ~20g = 180kcal more + ~50kcal from some fibre. Probably very hard to maintain, add butter to taste.</p><p>The cool thing about this “high-protein-keto” approach is that we can always freely add more fat if that helps with hunger and energy levels without “breaking” the low-insulin fat-burning setup.</p><p>I’ll be trying this out in the coming fall!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=cbe32d0096ab" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Veselības strukturālie pamati]]></title>
            <link>https://medium.com/@augustsbautra/vesel%C4%ABbas-struktur%C4%81lie-pamati-3f6f250c4309?source=rss-47874e2a695f------2</link>
            <guid isPermaLink="false">https://medium.com/p/3f6f250c4309</guid>
            <category><![CDATA[chronic-illness]]></category>
            <category><![CDATA[longevity]]></category>
            <category><![CDATA[diet]]></category>
            <category><![CDATA[health]]></category>
            <dc:creator><![CDATA[August Bautra]]></dc:creator>
            <pubDate>Sun, 27 Oct 2019 20:36:28 GMT</pubDate>
            <atom:updated>2019-10-27T20:36:28.004Z</atom:updated>
            <content:encoded><![CDATA[<p>Cilvēki mani pazīst kā #keto čali. Es visiem stāstu, ka jāpārtrauc ņammāt ogļhidrātus, un to vietā jāēd tauki, galvenokārt sviests un kokosriekstu eļļa. Prātojumi, uz kuriem balstīts šis domu gājiens, daudziem ir zināmi, un nebūs daļa no šī raksta. Tā vietā, es izklāstīšu jaunu, papildinošu, un, iespējams, <strong>par keto nozīmīgāku ideju veselībā</strong>.</p><p>Pagājušogad <a href="https://www.youtube.com/channel/UCSIUpXeC1QEjNm54X7KylkQ">AncestryFoundation</a> YouTube kanālā man bija tas prieks noskatīties <a href="https://www.youtube.com/watch?v=bWFygvz7klk">Krisa Knobbes prezentāciju</a> par to, ka makulas deģenerācija ir ierindojama blakus citām pazīstamajām Rietumu deģeneratīvajām slimībām, piemēram sirds slimībām un vēzim, taču, lai arī viņa tēze šķita acīmredzami patiesa, un tās stiprināšanai piedāvātie dati, dažādu populāciju lietotā uztura un attiecīgo makulas deģenerācijas gadījumu īpatsvara attiecība, šķita pārliecinoši, viņa teikto es vienkārši noarhivēju interesanto, bet ne tieši man noderīgo faktu vācelē.</p><p>Mana attieksme mainījās, kad noskatījos <a href="https://www.youtube.com/watch?v=pHnPinYI2Yc">viņa 2019. gada prezentāciju</a>. Visticamāk, ka savā ziņā pareizo intuīciju uzpumpēja arī <a href="https://www.youtube.com/watch?v=F5HXCfimEa4&amp;t=4s">Rona Rousdeila prezentācija par Varburga efektu</a>.</p><h4>Laba uztura definīcija</h4><p>Līdz vēmienam dzirdēts, ka jāēd sabalansēts, uzturvielām bagāts uzturs. Dārzeņi, augļi, šķiedrvielas. Gaļa. Nē, pag, tā tomēr ir slikta? Treknu mazāk. Utt. Utjp.</p><p>Pakāpsimies soli atpakaļ.</p><p>Kas ir kopsakarīgais, vispārīgais princips, kas diktē, kas ir labs, un kas slikts uzturs? Kas ir labs govij varbūt nebūs labs omāram. Kas ir labs pieaugušajam var nebūt labs bērnam. Šķiet, tā dižā kopsakarība tomēr būs evolūcija. Sugas īpatnim labs uzturs būs tāds, kas sader ar evolucionāri iemantotajām vielmaiņas vajadzībām, gremošanas spējām un ēšanas praksi. Šāds redzējums ir konservatīvs. Tas saka, ka zinot pēdējo 100 000 gadu vēsturi un paradumus, mēs ar zināmu drošību varam teikt, ka cilvēkam par labu nāk dzīvnieku izcelsmes produkti, īpaši tauki un orgānu gaļas, kā arī, ka ar lielu skepsi uztverami pēdējo 100 gadu jaunievedumi pārtikā — rafinēts cukurs un milti, un sēklu eļļas. Attiecīgi ar skepsi uztverami kārtējās kompānijas jaunību/veselību/skaistumu/spēju uzlabojošo produktu mārketinga materiāli, jo viss, ko mēs jebkad esam mēģinājuši, ir atdūries pret vielmaiņas slieksni un evolucionāru balansu. Klasiskie piemēri ir morfijs, koka, kafija, nootropiķi, efedrīns, viagra, vairogdziedzera hormonu injekcijas — visām šīm “terapijām” ir īslaicīgs efekts, kam ķermenis aptuveni divu nedēļu laikā pielāgojas un atgūst homeostāzi.</p><p>Labs uzturs nodrošina to, kas vajadzīgs organisma bioloģisko pamatfunkciju veikšanai, proti šūnu spējai dzīvot un dalīties, kas vienkāršā valodā nozīmē kalorijas un būvelementus jaunām šūnām. Līdz šim esmu īpašu vērību pievērsis tieši kaloriju avotam, bet izrādās, ka tieši būvelementu adekvāts daudzums un sastāvs var spēlēt visnozīmīgāko lomu, īpaši ilgtermiņā.</p><p>Labs uzturs ir gluži kā ētiska rīcība — tam var pieturēties visu mūžu, un krīzes brīžos to dara vairāk, ne mazāk, jo tas ir vienīgais veids, kā atgriezties normālībā.</p><h4>Vaina uzturā</h4><p>Divi īpaši svarīgi slaidi no Krisa prezentācijas:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*QAeogWELYQhwBe7FLtenlA.png" /><figcaption>Sirds slimību un sēklu eļļu patēriņa kopsakarība</figcaption></figure><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*DGZB62F3FXQgma8aNncyOw.png" /><figcaption>Dažādu pārtikas tauku piesātinājums</figcaption></figure><p>Būtībā, mēs redzam, ka pēdējos 100 gados dramatiski kāpis uzturā patērēto sēklu eļļu apjoms, un, ka tas korelē ar ar (sic!) sirds slimībām mirušo skaitu. Skeptiskākie lasītāji aizrādīs, ka korelācija nenozīmē cēloņsakarību. Citi aizrādīs, ka pēdējo 50 gadu pētījumi rāda, ka aizstājot piesātinātos taukus ar polinepiesātinātiem, sirds slimību risks samazinās.</p><p>Kā salāgot mums pieejamos novērojumus? Kā piesātinātie tauki var būt atbildīgi par sirds slimībām, ja to patēriņš nav mainījies? Sekos raksta spekulatīvā daļa, un, ja nepiekrītat piedāvātajām premisām, attiecīgi nevarēsit sagremot secinājumu.</p><p><em>Domu gājiens:</em></p><p>20. gadsimta sākumā nekur pasaulē vēl nebija pieejami modernie pārstrādātie produkti. Visi cilvēki, pēc definīcijas, ēda nepārstrādātu, svaigu, vēsturiski atzītu pārtiku, kura pēc iespējas tuvojās mums tagad zināmajiem neaizstājamo uzturvielu rādītājiem, īpaši, ~7-15% no kalorijām proteīnā (galvenokārt no piena produktiem), un vismaz 30% no kalorijām no taukiem, panākot ~1:1–1:2 omega-3 un omega-6 tauku proporciju. Deģeneratīvās slimības praktiski netiek novērotas.</p><p>Savukārt 21. gadsimta sākumā cilvēki lielākajā daļā, īpaši Rietumu, pasaules, pārtiek no pārstrādātas, ilgi glabātas pārtikas, kas stipri atšķiras no evolucionāri pielāgotas. Īpaši izceļams, ka ārkārtīgi mainījusies ēsto tauku omega-3:omega-6 attiecība; no 1:2 uz, vidēji, 1:15, kā arī stipri palielinājies cukura daudzums uzturā. Deģeneratīvās slimības ir vadošais nāves un nespējas iemesls pasaulē.</p><p><em>Secinājums:</em></p><p>Deģeneratīvās slimības izraisa neadekvāts strukturālo komponentu saturs uzturā, īpaši pārlieku augsts omega-6 un trans-tauku saturs.</p><h4>Slimības izcelsme</h4><p>Strukturālajā aspektā tauki un olbaltumvielas uzturā ir daudzkārt nozīmīgāki par ogļhidrātiem, jo tos ne tikai dedzina enerģijai, bet arī var izmantot kā izejvielas šūnu sastāvam — olbaltumvielas nukleotīdiem un receptoriem, un taukus pašām šūnu membrānām.</p><p><a href="https://en.wikipedia.org/wiki/Cell_membrane#/media/File:Cell_membrane_detailed_diagram_4.svg">Cell membrane</a></p><p>Ja uzturā tauku ir nepietiekami, cilvēka ķermenis radīs taukus no pieejamajiem ogļhidrātiem, un tie galvenokārt būs piesātinātie tauki, kas līdzinās speķim (tādēļ cūkas ir pazīstamas kā ļoti tuvs cilvēka analogs pētījumos, kur šis fakts ir nozīmīgs). Fakts, ka “priekšroka” tiek dota piesātinātiem taukiem, lai tos izmantotu membrānu veidošanai manuprāt ir ļoti spēcīgs evolucionāra apsvēruma identifikators, acīmredzot piesātinātās taukskābes ir labāks membrānu materiāls. Un nav grūti saprast, kādēļ — piesātinātas taukskābes ir garas, taisnas molekulas, kas lieti noder ūdeni necaurlaidīga fosfolipīdu slāņa veidošanai. Turpretim jebkura veida ne-piesātinājums, kā tas ir taukskābēs, kas atrodamas sēklu eļļās, noved pie molekulas saliekšanās.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*mPKtk6ELbEE1ZsLhPoJV7w.jpeg" /></figure><p>Fosfolipīdi ar šķībām “kājām” rada neefektīvas membrānas. Liels neefektīvu membrānu īpatsvars noved pie šūnu bojāejas un organisma pāragras novecošanas — deģenerācijas. Bojātas membrānas sirdī noved pie sirdstriekas, bojātas membrānas smadzenēs — pie Alcheimera slimības, utt.</p><h4>Kā būt</h4><p>Jāparūpējas, ka ķermenī ir pēc iespējas mazāk omega-6 polinepiesātināto tauku. Praksē tas nozīmē ēst pēc iespējas mazāk (ideālā gadījumā nemaz) tā dēvēto “augu” eļļu. Bet var iet vēl tālāk un samazināt uzturā lietoto daudzumu produktu, kuros ir daudz nepiesātināto taukskābju, piemēram, riekstus. <a href="https://en.wikipedia.org/wiki/Fat">Wikipedijas lapā par taukiem</a> labajā pusē ir noderīgs grafiks.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/289/1*EE1ZkBAx2TLbZ2IYaS-EPQ.png" /></figure><p>Redzams, ka “augu” eļļas — rapšu, kukurūzas, sojas, arī saulespuķu, ir ar augstu nepiesātināto tauku saturu un attiecīgi nav vēlamas (olīveļļa, protams, ir izņēmums). Attiecīgi, piena produkti un liellopu gaļa ir ar viszemāko piesātināto tauku saturu, kas labi ilustrē šo lopu milzīgo nozīmi nācijas veselībā ne tikai pagātnē, bet arī turpmākajā simtgadē.</p><p>Par nožēlošanu Kriss min, ka membrānā jau esošus polinepiesātinātos taukus maģiski ārā dabūt nevar. Jāpaiet līdz pat 600 dienām. Šūnām principā jāiet bojā un jaunām, taisītām no veseliem taukiem, jāstājas to vietā. Tās, savukārt, ir sliktas ziņas sirds veselības sakarā, jo sirds audu šūnas, tā pat kā smadzenes, teju nedalās. Ja bērnībā baroja ar **du, ir liela varbūtība, ka bojājums ir neatgriezenisks un būs jāmeklē papildu stratēģijas. Bērnu uzturam ir milzu nozīme!</p><p>Mans veselīgo “tauku top” ir:</p><ol><li>Kokosriekstu eļļa — teju 100% piesātināta un pa pusei MCT, kas sekmē ketozi, vismaz 30g dienā, yum!</li><li>Sviests, vismaz 40g dienā.</li><li>Liellopu tauki (praksē no trekna steika) 10g dienā.</li><li>Olīveļļa (nekad uz pannas, izsmidzināta uz salātiem) 5g dienā, labs neaizstājamo omega-6 avots.</li><li>Speķis, diezgan tuvs olīveļļai, labs vajadzīgo omega-6 avots, bet tāpēc, ka ir gardākas alternatīvas, reti ēdu vairāk par 20g dienā.</li><li>Eļļas zivis (forele, lasis) — teju vienīgais veids kā uzņemt neaizstājamo omega-3 ar pārtiku, var ēst, cik lien.</li><li>Zivju eļļas kapsulas — ekonomiskākais un izturamākais omega-3 avots vidējajam latvietim. Pa sešām 2g kapsulām dienām kopā ar vakariņām = 12g dienā.</li></ol><p>Ar šādām dozām man sanāk ~100g tauku dienā, kas skaitās “high-ish, pre-keto fat, low-ish carb” un omega-3:omega-6 attiecību 2:1, drošībai.</p><p>Ēduši veseli!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=3f6f250c4309" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[RSpec, Factory Girl, and Ruby: a Primer in Rails Test Performance]]></title>
            <link>https://medium.com/@augustsbautra/rspec-factory-girl-and-ruby-a-primer-in-rails-test-performance-8ec0baaa19e3?source=rss-47874e2a695f------2</link>
            <guid isPermaLink="false">https://medium.com/p/8ec0baaa19e3</guid>
            <category><![CDATA[rails]]></category>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[rspec]]></category>
            <category><![CDATA[testing]]></category>
            <dc:creator><![CDATA[August Bautra]]></dc:creator>
            <pubDate>Sat, 14 Oct 2017 18:09:12 GMT</pubDate>
            <atom:updated>2019-02-10T09:22:53.999Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<p>In this post I will compare the various setup strategies available when testing Rails with RSpec, and make recommendations as to the use-cases of each.<br>Information therein may help you improve your test suite execution speed.</p><h3>The environment</h3><p>We will be looking at a <a href="https://github.com/Epigene/rails-example">naive test app</a> running Rails v5.1.4 and Ruby 2.4.2. Furthermore, the app uses RSpec v3.6.1 with FactoryGirl v4.8.1 for specs.</p><h3>The strategies</h3><ol><li>FactoryGirl.create</li><li>FactoryGirl.build</li><li>FactoryGirl.build_stubbed</li><li>instance_double</li><li>new</li></ol><h4>1. FactoryGirl.create</h4><p>This strategy is the slowest because it actually stores objects in the database. Use for testing scopes, associations, resource changes in controller actions, wherever you need an actual database id for things to work.</p><h4>2. FactoryGirl.build</h4><p>This strategy does not interact with the database (yet), but allows the possibility. Use in the limited special occasions when you need to test logic that pertains to “as things get put in the database” events, like callbacks, attribute sanitation, etc.</p><h4>3. FactoryGirl.build_stubbed</h4><p>This ought to be the preferred strategy. It does not interact with the database, and, unlike regular build, makes the built object (and any associations the factory may set up) in-memory-only, preventing database interaction and ensuring performance.<br>Use everywhere you need rich actual objects that will not interact with the database, like model and service class method unit tests.</p><h4>4. instance_double</h4><p>This RSpec-provided strategy is perfect for when you have a method that calls another object’s method(s). Since you need not test the behavior of the other object, you can use instance_double to safely mock the value returned. RSpec will even make sure the original object responds to the method you are trying to mock, preventing missed API changes.</p><h4>5. new</h4><p>This is an ingenious, super-fast plain-Ruby strategy perfect for use in counter-examples; hampered only by its limited applicability.</p><h3>The Comparison</h3><p>For comparisons to be fair, there need to be four strategy competition groups, comparing performance of a test that the least complex strategy can be used for.<br>For example, what can be tested using new can also be tested using all other more complex strategies, but what can be tested with FactoryGirl.build, can only be also tested using FactoryGirl.create.<br>Feel free to clone to test app and run the benchmarks yourself with:</p><pre>$ rspec spec/setup_benchmark.rb<br># and look at the output of spec/group_profiling_results.csv</pre><p><em>The raw data I got on my machine can be viewed </em><a href="https://gist.github.com/Epigene/aeb3fbe1cd5061cf7bda58e8c755bbbc"><em>here</em></a><em>.</em></p><h4>1st Bout: Comparing new with all other strategies.</h4><p>Let’s test a simple method that returns a boolean value based on a field’s value. The Book#vampire_title? method returns true if a book seems to be about vampires.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/a89202f9a7c51f151da53d2881ba95f5/href">https://medium.com/media/a89202f9a7c51f151da53d2881ba95f5/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f924dd36fbb4bbd4392ef8b5bcda25fb/href">https://medium.com/media/f924dd36fbb4bbd4392ef8b5bcda25fb/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*ncraFxv6aQ6CqxufV5DV3Q.png" /></figure><h4>2nd Bout: Comparing instance_double with FactoryGirl.build_stubbed, FactoryGirl.build, and FactoryGirl.create</h4><p>Let’s test a method that basically wraps an association’s method. The Book#by_bce_author? returns whatever Author#bce? returns. In this case, true if the author was born before current era.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8a2ac8153fa8cfc569de98a53506e74c/href">https://medium.com/media/8a2ac8153fa8cfc569de98a53506e74c/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/b2dbe3d82af9a309bc654f4588474f80/href">https://medium.com/media/b2dbe3d82af9a309bc654f4588474f80/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*frnlevOFSlq25Gk7LwTPEw.png" /></figure><h4>3rd Bout: Comparing FactoryGirl.build_stubbed with FactoryGirl.build and FactoryGirl.create</h4><p>Let’s test a method that needs FactoryGirl’s powerful setup capabilities. Book#with_characteristics? returns true if the passed arguments match the book’s author and publisher.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4ce298237bcb641c70636e6a71a1aa8c/href">https://medium.com/media/4ce298237bcb641c70636e6a71a1aa8c/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/e23d5aa2999cc716da84416e6cf4c122/href">https://medium.com/media/e23d5aa2999cc716da84416e6cf4c122/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YGNdjIAWAxqBJ4n4lNFN0w.png" /></figure><h4>4th Bout: Comparing FactoryGirl.build with FactoryGirl.create</h4><p>Let’s test an after-save callback.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/58047876716c06de8bbddbc22ace4c0d/href">https://medium.com/media/58047876716c06de8bbddbc22ace4c0d/href</a></iframe><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/34a3cad17dc18ef54e27b250292e16db/href">https://medium.com/media/34a3cad17dc18ef54e27b250292e16db/href</a></iframe><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*YpUfD97lDXzJkmSMUhTq6g.png" /></figure><h3>The Discussion</h3><p>Create is clearly the slowest, try to avoid it.</p><p>#instance_double being faster than #new was a bit of a surprise for me, but it makes sense, initialization may trigger all kinds of Rails code (like field defaults), whereas #instance_double merely makes a mock object with specified (if any!) return values for called methods.</p><p>Always prefer FactoryGirl.build_stubbed to FactoryGirl.build when not persisting the records, it is~20–50% faster.</p><p>FactoryGirl.build is not significantly faster than FactoryGirl.create in my benchmarks, which signifies that most time is spent setting up Ruby objects not writing to database. I use DatabaseCleaner with transaction directive though, so I may not be seeing the full impact of DB writes.</p><p>Please keep in mind that cost of FactoryGirl.build and FactoryGirl.create can grow rapidly as your factory association structure grows in complexity, the one in my benchmarks is trivial; all the more reason to use FactoryGirl.build_stubbed.</p><h3>The Thanks</h3><p>You, for reading!<br>Ben Eddy for <a href="https://www.foraker.com/blog/profiling-your-rspec-suite">RSpec suite profiling insight</a>.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=8ec0baaa19e3" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Performant SQL queries in Rails, an odyssey]]></title>
            <link>https://medium.com/@augustsbautra/performant-sql-queries-in-rails-an-odyssey-1a679834fdb1?source=rss-47874e2a695f------2</link>
            <guid isPermaLink="false">https://medium.com/p/1a679834fdb1</guid>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[sql]]></category>
            <dc:creator><![CDATA[August Bautra]]></dc:creator>
            <pubDate>Sat, 29 Jul 2017 20:49:22 GMT</pubDate>
            <atom:updated>2017-07-29T20:53:56.366Z</atom:updated>
            <content:encoded><![CDATA[<figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*CPeO7CQjarrIwxJj4wkDng.jpeg" /><figcaption><strong><em>Stylized image of a fractal</em></strong><em>. [</em><a href="http://digitalartofjax.com/wp-content/uploads/2016/10/fractal.jpg"><em>fractal</em></a><em>, </em><a href="http://digitalartofjax.com/">digitalartofjax.com</a><em> CC 2.0]</em></figcaption></figure><p>I am a Rails developer without formal software development training. I started out without having heard of Ruby, Rails, grep or RegEx. I knew zero SQL. But I learned fast and I could solve 99% of problems I was facing in a semi-usable way. Then I learned O notation and became acutely aware that good solutions must be performant in theory, not only the initially small database.</p><h4>The problem</h4><p>It really is very simple. There are Users who have many Posts. We want a query that collects only the posts that are users’ last and order them, latest posts first.</p><p>Ordering is simple</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/94be04ba76e4a7c7a8594940fc5be20c/href">https://medium.com/media/94be04ba76e4a7c7a8594940fc5be20c/href</a></iframe><p>But what of the core query? How to select only the last association? After several brave attempts I was forced to admit that my ActiveRecord and SQL-fu was nowhere near strong enough to get at this cleanly. Enter…</p><h4>The ugly</h4><p>I had an understanding of how to solve this problem in Ruby. I had to loop over all users who have posts and get their last post.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/56838d49dadcd2e0f849beef83430cb9/href">https://medium.com/media/56838d49dadcd2e0f849beef83430cb9/href</a></iframe><p>This code started to take tens of seconds to execute once users got into thousands, but it worked in production for a while.</p><h4>The bad</h4><p>Soon it became clear that the first implementation had two severe downsides. It was very slow at scale and since it returned an array, not an ActiveRecord query object, it could not be easily extended with other scopes.</p><p>I still knew not how to write an efficient query, but I had an idea how to refactor the collection so it was a query object.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/2afef98f6578d00c18c9795059ab5fe7/href">https://medium.com/media/2afef98f6578d00c18c9795059ab5fe7/href</a></iframe><p>The approach to pluck ids and then feed them back into where(id: ids) was with me for a long time. It got the job done.</p><h4>The OK</h4><p>Eventually it became clear that the loop over users was a no-no and I was given time and pointers to learn some SQL. I learned that SQL grouping and aggregate function MAX would serve us well in solving the problem. This achieves the needed results, but with a sub-query.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/59e8873c99c6db0de26ab1a9bd3e63dd/href">https://medium.com/media/59e8873c99c6db0de26ab1a9bd3e63dd/href</a></iframe><h4>The WOW</h4><p>Recently even the OK solution started to falter and I was beginning to fret that this time I will not be able to get much performance gains. Boy, was I wrong.</p><p>I wanted, finally, to implement an all-SQL, clean solution that would be the theoretically most performant one. Luckily, my knowledge had greatly grown since last I tackled The Problem and I had a clear idea of how to go about solving it.</p><p>First, I had to find an answer to the question</p><blockquote>“How to execute arbitrary SQL code in Rails and get back a query object?”</blockquote><p>To get at this I prepared a <a href="https://github.com/Epigene/rails-example">test app</a> that mirrored the common association pattern I had had trouble with. Then I wrote specs for scopes I needed to work and bechmarks for different implementations.</p><p>There were three competing approaches I had to test:</p><ol><li><a href="https://stackoverflow.com/a/36631116/3319298">Fancy subquery approach with </a><a href="https://stackoverflow.com/a/36631116/3319298">.from</a></li><li>Model.find_by_sql(query)</li><li>Model.connection.execute(query)</li></ol><p>I quickly abandoned the .from approach as it would require a subquery like the solution I already had and focused instead on writing the raw SQL snippet I would feed to find_by_sql and connection.execute.</p><p>Then it dawned on me I had previously used raw SQL snippets (primitive ones) in queries by using them as joined tables. I decided to try this technique alongside the 2. and 3. approach.</p><blockquote>The joins solution is at least 200 times faster than the previous one!</blockquote><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/756308d2a179c9cd0643a165a6886b0b/href">https://medium.com/media/756308d2a179c9cd0643a165a6886b0b/href</a></iframe><h4>The takeaway</h4><blockquote>Ruby is slow, SQL is blazing fast, take pains to solve data problems SQL-side</blockquote><ol><li>Use raw SQL and insert it in ActiveRecord’s joins statements for massive performance boosts.</li><li>Do your best on problems, and anticipate that as you gain experience, solutions that are orders of magnitude better will present themselves.</li><li>Be open to new ideas; test and benchmark competing ideas. Pick the solution that fits best for your use-case.</li></ol><h4>PS</h4><p>If you are making queries to Rails record’s :created_at field, be sure to add indexes for them. By default they are not indexed!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=1a679834fdb1" width="1" height="1" alt="">]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Good Enough To Get Better]]></title>
            <link>https://medium.com/@augustsbautra/good-enough-to-get-better-74d2714a0c60?source=rss-47874e2a695f------2</link>
            <guid isPermaLink="false">https://medium.com/p/74d2714a0c60</guid>
            <category><![CDATA[education]]></category>
            <category><![CDATA[chess]]></category>
            <category><![CDATA[programming]]></category>
            <dc:creator><![CDATA[August Bautra]]></dc:creator>
            <pubDate>Tue, 17 May 2016 18:53:57 GMT</pubDate>
            <atom:updated>2016-05-17T18:56:34.351Z</atom:updated>
            <cc:license>http://creativecommons.org/licenses/by/4.0/</cc:license>
            <content:encoded><![CDATA[<p>This is an essay about knowledge transfer — teaching, learning and competence.</p><h4>The “goal” of learning</h4><p>I have always been passionate about learning, about discovering new things and explaining them first to myself and then to others. I believe education, as in providing people with skills and knowledge that gives them more and better options in life, to be among the most efficient social betterment tools available.</p><p>Over the years I have learned and found myself teaching several niche skills, like practicing a #ketogenic way of life, programming Ruby (on Rails) and playing chess.<br>Learning about keto directs my choice of food in a scientific manner and helps me avoid health problems. I will never reach a stage where I “know keto”, it’s an ongoing process.<br>Learning about programming helps me be more productive and happy at my job — by learning I can get more done by doing less. I will never reach a stage where I “know programming”, it’s an ongoing process.<br>Learning about chess helps me make better moves and put the hurt on opponents. I will never reach a stage where I “know chess”, it’s an ongoing process.</p><p>In retrospect, there is a crucial difference between the “goal” of learning either of these things and skills I obtained in school. The difference lies in the answer to the question “what do I want to be able to do once I learn this skill?”. In the case of the recent trio, the answer is, in essence, “I want to be able to solve problems (better)”. However, of the things I learned in school, I can not say this.<br>The purpose of learning to read — to know how to read.<br>The purpose of learning math — to know math.<br>The purpose of learning history — to know history.</p><p>Looking back on my education, both formal and informal, as well as my own teaching efforts, I have come to a realization that the most efficient outcome of learning is reaching a stage where any further learning can be achieved on one’s own, without any additional “teaching”. Furthermore, this state ought also be full of not only possibility, but desire to learn more.</p><p>I believe that optimizing for this would yield a society that is far more intellectually robust and capable of greater ingenuity and discovery. Optimizing for such learning outcomes would also require a considerable re-think in terms of formal education.</p><p>The basis of this bootstrapping education would be formed from two tiers of skills:</p><ol><li>Understanding and living efficaciously in the world of the present.</li><li>Having bold ideas about life in the future.</li></ol><h4>The bootstrap education</h4><p>Recently I was considering how I would go about teaching chess to an adult who has never played the game.<br>This is no trivial challenge. I would definitely have to explain how the pieces move, what the objective is, what the general rules are. That would enable my pupil to “play the game”, but, frankly, with such bare-bones instruction, their game would be poor and would not provide much enjoyment to anyone. And there is so much more to teach — algebraic notation to “read and write chess”, chess etiquette, openings and their tactical ideas, endgame strategy, tactics, pawn structure, position quality, material, using engines in analysis, etc. etc. What should dictate the priority of instruction?</p><p>It seems to me that an excellent strategy and goal for teaching chess could be to get my pupils good enough, so that they become even better after the tutoring is over.<br>That would mean the absolute essentials, but also some “chess fluency” skills like reading algebraic notation, analyzing a position and determining the most promising moves and the principles behind it, as well as providing inspiration to play chess, be it with igniting a pupil’s competitive spirit, or giving historical context of great characters in chess and their achievements.</p><p>We could structure general learning in a similar manner.<br>Teach reading, writing and math, yes. Teach critical thinking, general science, programming and health for that world literacy. Teach expecting the inevitable in technology and personal life for that bold future.</p><p>And, yes, absolutely teach programming. Recently there was the <a href="http://techcrunch.com/2016/05/10/please-dont-learn-to-code">Please don’t learn to code</a> VS <a href="https://medium.freecodecamp.com/please-do-learn-to-code-233597dd141c#.l9meg5ke7">Please do learn to code</a> and the pro movement clearly has the upper hand, especially with the point that</p><blockquote>Coding isn’t some niche skill. It really is “the new literacy.”</blockquote><p>Please consider where you can become good enough to get better or help others get good enough to get better, go the extra mile and make a permanent change.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=74d2714a0c60" width="1" height="1" alt="">]]></content:encoded>
        </item>
    </channel>
</rss>