<?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 Hung Doan on Medium]]></title>
        <description><![CDATA[Stories by Hung Doan on Medium]]></description>
        <link>https://medium.com/@hdoan741?source=rss-da95afd45291------2</link>
        <image>
            <url>https://cdn-images-1.medium.com/fit/c/150/150/2*Lbqlq1DVM6YLu5Sj7BfCww.jpeg</url>
            <title>Stories by Hung Doan on Medium</title>
            <link>https://medium.com/@hdoan741?source=rss-da95afd45291------2</link>
        </image>
        <generator>Medium</generator>
        <lastBuildDate>Mon, 23 Nov 2026 03:52:30 GMT</lastBuildDate>
        <atom:link href="https://medium.com/@hdoan741/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[Bringing Coda up to Date: 25-hours days and other things I learned when migrating from moment date…]]></title>
            <link>https://medium.com/coda-project/bringing-coda-up-to-date-25-hours-days-and-other-things-i-learned-when-migrating-from-moment-date-5ad452427c28?source=rss-da95afd45291------2</link>
            <guid isPermaLink="false">https://medium.com/p/5ad452427c28</guid>
            <category><![CDATA[engineering]]></category>
            <category><![CDATA[datetime]]></category>
            <category><![CDATA[momentjs]]></category>
            <category><![CDATA[luxon]]></category>
            <category><![CDATA[coda]]></category>
            <dc:creator><![CDATA[Hung Doan]]></dc:creator>
            <pubDate>Mon, 16 May 2022 21:30:45 GMT</pubDate>
            <atom:updated>2022-05-16T21:30:45.710Z</atom:updated>
            <content:encoded><![CDATA[<h3>Bringing Coda up to date: 25-hour days and other things I learned when migrating from moment date library</h3><h4>Escapades in JavaScript date/time handling.</h4><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*8f399rq3ZHetn1tA_YHBiw.jpeg" /></figure><p>Date is a common concept — we use date and time every day when talking with each other. However, I realized I knew next to nothing about its technical aspects until I worked on improving support for international dates on Coda. We had a mysterious bug: there were reports from a few users that our Date operations, on some rare occasions, produce Date results that are off by a few minutes. Below is an example where a Coda doc is set to <em>Asia/Kuala_Lumpur </em>timezone and a user finds that a date they entered is off by 9 minutes when referenced in another column.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/984/0*tV2JpnxZ2sKJHkY9" /></figure><p>The same object, but somehow off by 9 minutes.</p><p>This is quite bizarre. How could the same value show up differently in another place? I even double-checked that the underlying value was the same. It turned out it was because of a bug with the moment, the date library we’ve been using at Coda.</p><p>moment was everyone’s date library of choice, but it has fallen behind and is <a href="https://momentjs.com/docs/#/-project-status/">no longer actively maintained</a>. As we invest in improving support for international users, we wanted to build on a stronger foundation. I kicked off work to replace the library, but little did I know what I would get myself into. Read on to hear about my escapades in javascript date/time handling and what I found the best library to be.</p><h3>How hard it would be to create a date in a given timezone?</h3><p>Coda supports various <a href="https://coda.io/formulas#Created">Date formulas</a>. Makers can create dates from components, add and subtract date, and add custom date inputs that should all work in the user-chosen timezone. In order to support makers around the world, we had to find a library that supports a wide set of date time operations for every timezone.</p><p>The first test I did was to create a date with different date components (year, month, day) and time components (hour, minute, second) in a specific timezone. It seemed like a simple task until I understood how timezones work. Let’s take a step back to understand the fundamentals of date, time and timezone and why it’s a challenge to handle.</p><h3>Date, timezone, and offset</h3><p>If I ask you which date and time it is currently, I’m sure you can answer it without blinking, something like “It’s March 25, 2022, at 3pm.” If I relay the same information to someone on the other side of the Earth, would they agree? No! They would say that it’s March 26, 2022, at 5am. It’s a different time of day and even a different date for them. Although we’re at <em>the same moment in time</em>, the date components are different! To communicate this difference, we usually denote the date with a <strong>timezone</strong>, and we can convert the date components from one timezone to another based on their <strong>timezone offsets</strong>. The offset is relative to <a href="https://en.wikipedia.org/wiki/Coordinated_Universal_Time">UTC</a>, a standard time recognized around the world. I’m in California, USA, so my current timezone is PDT (Pacific Daylight Time), and it’s -7h from UTC time. Someone in Vietnam is in Indochina Time, which is +7h from UTC time.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*ilcf_tLBazwrc_bg" /></figure><p>Javascript comes with a standard Date object, but it comes with a severe limitation: no support for custom timezone (it implicitly uses the user’s local timezone). We would have to go through a few hoops in order to create a date a specific timezone with JS Date. Specifically, we have to find out the timezone offset of the date in the desired timezone. And here is why it’s not easy: timezone offset of the same location may <a href="https://www.timeanddate.com/news/time/">change over time.</a> A famous example is when <a href="https://www.timeanddate.com/news/time/samoa-dateline.html">Samoa switched time zones</a> and effectively redrew the International Date Line. There is also a recurring version of this that’s familiar to people in the US and many countries: Daylight Savings Time. Every year, there will be about 5 months where California (America/Los_Angeles) timezone has -8 hours offset, and 7 months where the offset is -7 hours. To make things even more confusing, the day that it happens changes every year!</p><blockquote>Fun fact: Standard time zones are introduced fairly recently in the history of humankind! <a href="https://www.history.com/news/when-did-the-united-states-start-using-time-zones#:~:text=On%20November%2018%2C%201883%2C%20America&#39;s,zone%2C%20all%20clocks%20were%20synchronized.">Before 1883</a>, every city in the U.S. had its own time, and the time in each city could vary by a few minutes. It created so much problem with train scheduling that the Railroad companies started using standard time zones and the rest is history.</blockquote><p>It’s complex to construct a date in the right timezone, and not every Javascript Date library out there supports it.</p><h3>How hard would it be to add one day to a date?</h3><p>Another building block of date manipulation on Coda doc is adding or subtracting from a date. Adding one day to a date is a trivial task for humans to do. One day after March 25, 2022 should be March 26, 2022, and one month after this date would be April 25, 2022, right? What would be so hard about it? Let’s explore this problem through the lens of a computer system.</p><h3>Unix timestamp</h3><p>When given a date, the computer doesn’t store 6–7 different numbers representing the different date components. It’s smarter! It stores a single number, a <strong>timestamp</strong>, representing a specific moment in time. This number represents the number of millisecond from an <a href="https://en.wikipedia.org/wiki/Epoch_(computing)">epoch</a> moment in time (a common one is 1/1/1970 00:00:00 in UTC). Every moment has a unique timestamp, no matter which timezone it is. Based on the timezone offset, this number can be converted to the time at a given timezone and derive the date components.</p><p>It’s simple and effective at reducing the complexity of storing time. But not when you want to do some math with it. A naive approach to date math would be adding the number of milliseconds to the timestamp. It quickly fails when you realize that:</p><ul><li>A year doesn’t always have 365 days</li><li>A month doesn’t always have 30 days</li><li>And a day doesn’t necessarily have 24 hours.</li></ul><p>Wait, what? A day doesn’t always have 24 hours? That’s right. Remember that DST may change a timezone offset forward or backward by 1 hour? Let’s look at California DST changes this year:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CVQ2QvotwrbW-I1X" /></figure><p>On March 13, 2022, the Pacific Time (PT) timezone switches from being -8 hours from UTC to -7 hours from UTC. This day loses 1 hour because after 01:00 AM, it will be 03:00 AM! Worry not, on the DST end day, November 6, 2022, the day will have 25 hours to make up for the loss! To everyone who wishes for 25 hours a day: your wish is granted 1 day a year. Cheers!</p><blockquote>To everyone who wishes for 25 hours a day: your wish is granted one day a year!</blockquote><p>A better way to approach date math is differentiating <a href="https://moment.github.io/luxon/#/math">calendar math and time math</a>. When adding days, months, years, we should add directly to that component instead of adding milliseconds. With that, we circle right back to the first problem, which is creating a date from specific components.</p><p>Let’s take a moment to appreciate the challenges of handling timezones:</p><iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2F-5wpm-gesOY%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3D-5wpm-gesOY&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2F-5wpm-gesOY%2Fhqdefault.jpg&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/cd26eeff947a18b17d1c9ee5d54ac106/href">https://medium.com/media/cd26eeff947a18b17d1c9ee5d54ac106/href</a></iframe><h3>What is the best date library for timezone handling?</h3><p>It took me awhile to understand the challenge at hand and, frankly, I don’t want to be dealing with this madness. Thankfully, there are kind souls out there who has solved these challenges and made their code open sourced. I looked at popular open-sourced date libraries out there and tested how they faced against the tasks of handling timezones.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*k5K-_WYvZQfbYoSRATAk7g.png" /></figure><p>luxon was the clear winner! Join me in celebrating the existence of luxon! If you don’t have to deal with complex timezone logic, that’s fantastic; the other libraries may work for you. But if you do, you know which library to go to. Before I understood the complexity of handling timezone logic, I tried to compare the libraries based on fancy features like tree shaking, bundle size and so on. But now, I’m content that there is even something that handles all the messiness of timezone as well as luxon. In fact, I learned a lot about timezone math from luxon‘s fantastic <a href="https://moment.github.io/luxon/#/math">documentation</a>.</p><h3>Moment strikes back!</h3><p>We found the ideal replacement for moment, and it was luxon. It was time to migrate our data and codebase off the old library to the new one.</p><p>Now I can explain to you what caused the bug we saw at the beginning of the post. moment‘s approach is to bundle the timezone offset data with their library (in a different bundle called moment-timezone). However, it doesn’t and is not practical to bundle all the available timezone offset data. This creates a difference with modern Javascript Date formatting API supported by most browsers nowadays, Intl, which has a complete offset data bundled with it. Since Coda used Intl API to format a date, the same timestamp in moment is presented as a different time in Intl, hence the bug we observed. We don’t have this problem with luxon because they use Intl API under-the-hood for timezone offset data.</p><p>This brings up a migration challenge: if we simply swap out moment with luxon, many of our dates would stay wrong. We have to rewrite the timestamp that was handled wrongly by recomputing the timestamp with luxon. In general, if you migrate from moment to any recent date libraries, you may have to do this too, because they all use Intl API under-the-hood now.</p><p>Now, this “timezone offset change” actually can happen in reality without changing the date library. In fact, the US Congress is considering making DST time permanent in the U.S. If a date is converted to timestamp, stored in a database and stashed away for two years, it might be read as a different date when the change is in-effect. Storing timestamp is <a href="https://codeblog.jonskeet.uk/2019/03/27/storing-utc-is-not-a-silver-bullet/">not a silver bullet</a>. Ideally, we should store a pair of timestamp and timezone offset to uniquely capture a moment in time <em>at the time it’s created.</em></p><h3>One more thing: date unit tests</h3><p>One of the challenges I faced when migrating our code was date-related unit tests. There are unit tests for our <a href="https://coda.io/formulas#Created">date formulas</a> and date utility functions. Since they are tested against multiple timezones, the result is usually timezone-dependent, and it’s a challenge to write the expected result. We ended up with various ways of writing imprecise expected results. Here are a few examples:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/801/0*qxDViUVnlMdydvDr" /></figure><p>They are imprecise because depending on the offset data used (moment API, Intl API, JS Date API), the timezone offset for a given Date &amp; timezone may be different, and the resulting date string may be different. They become a challenge when removing moment because there are a lot of confounding factors that relate to a test failing, such as a bug, converting function, or data specific to moment.</p><p>How might we achieve both simplicity of writing a unit test and the precision of the test? I spent a lot of time pondering this question, and this is where the fundamentals we learned above become useful: we need precise date components and timezone offset for the expected date. Here is a desired, standardized API that I created that offers a simple and easy-to-use API that fellow developers can use without having to think about timestamp and offset.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/800/0*aAMnRooSu24IpNq1" /></figure><p>Behind the scenes, the expected date string &amp; timezone are mapped to a validated timezone offset, based on sources like <a href="https://www.timeanddate.com/time/zone/usa/los-angeles?year=1899">TimeAndDate</a> website, producing an exact expected date. When a test fails, we would print out the differing component, making it simple to spot the difference between the actual date and the expected date. We can unify the way dates are tested in our code:</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/804/0*nJGRShqc5QNnRQc4" /></figure><p>Example of unit test changes.</p><h3>Takeaways</h3><p>The project has been a journey through the twists and turns of time! I’ve learned more about date, timezone, and offset than I ever wanted, but I can be the go-to person in the team for date-related matters now. The learning also made it a rewarding journey! Coda now has made away with bizarre Date bugs and has a better foundation to build more date time support for our users.</p><p>Here are a few useful takeaways:</p><ul><li>If you are serious about timezone support on your website or platform, pick luxon and never turn back!</li><li>Use a pair of timestamp and timezone offset to uniquely represent a moment in time. Timestamp alone is not enough, and timezones don’t have a fixed offset.</li><li>Lastly: Date &amp; Time handling is complex, <a href="https://www.youtube.com/watch?v=-5wpm-gesOY&amp;t=515s">avoid it if you can</a>!</li></ul><p>I was naive about the complexity of this problem when I jumped in, but hopefully, by sharing the knowledge here you’ll come to the problem more prepared than I am!</p><p>And if you are interested in deeply challenging technical problems like this, come join us; the Coda team is <a href="https://coda.io/jobs">hiring</a>!</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=5ad452427c28" width="1" height="1" alt=""><hr><p><a href="https://medium.com/coda-project/bringing-coda-up-to-date-25-hours-days-and-other-things-i-learned-when-migrating-from-moment-date-5ad452427c28">Bringing Coda up to Date: 25-hours days and other things I learned when migrating from moment date…</a> was originally published in <a href="https://medium.com/coda-project">Coda Blog</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Driving adoption of Sorbet static type checking in Rails]]></title>
            <link>https://medium.com/czi-technology/driving-adoption-of-sorbet-static-type-checking-in-rails-ff4e99296203?source=rss-da95afd45291------2</link>
            <guid isPermaLink="false">https://medium.com/p/ff4e99296203</guid>
            <category><![CDATA[ruby]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[static-typing]]></category>
            <category><![CDATA[sorbet]]></category>
            <dc:creator><![CDATA[Hung Doan]]></dc:creator>
            <pubDate>Tue, 01 Dec 2020 19:36:01 GMT</pubDate>
            <atom:updated>2020-12-01T19:36:01.247Z</atom:updated>
            <content:encoded><![CDATA[<iframe src="https://cdn.embedly.com/widgets/media.html?src=https%3A%2F%2Fwww.youtube.com%2Fembed%2FAPkKh40CF-8%3Ffeature%3Doembed&amp;display_name=YouTube&amp;url=https%3A%2F%2Fwww.youtube.com%2Fwatch%3Fv%3DAPkKh40CF-8&amp;image=https%3A%2F%2Fi.ytimg.com%2Fvi%2FAPkKh40CF-8%2Fhqdefault.jpg&amp;key=a19fcc184b9711e1b4764040d3dc5c07&amp;type=text%2Fhtml&amp;schema=youtube" width="854" height="480" frameborder="0" scrolling="no"><a href="https://medium.com/media/4519015e3205b01ede435c63d6eded0d/href">https://medium.com/media/4519015e3205b01ede435c63d6eded0d/href</a></iframe><p>At CZI, we’ve adopted <a href="https://sorbet.org/">Sorbet</a>, a fast and powerful static type-checking tool for Ruby. In our <a href="https://medium.com/czi-technology/static-type-checking-in-rails-with-sorbet-dc0414a502d9">previous</a> post, we talked about the technical challenges of adopting Sorbet in a Rails codebase, which led us to develop the <a href="https://github.com/chanzuckerberg/sorbet-rails">sorbet-rails</a> gem. After a year of using Sorbet, we have made significant progress covering our system with types. Currently, we have reached <strong>92% </strong><a href="https://sorbet.org/docs/metrics"><strong>file-level typed coverage</strong></a> and<strong> 75% </strong><a href="https://sorbet.org/docs/metrics#call-site-level-typedness"><strong>callsite-level typed coverage</strong></a>. Most importantly, Sorbet is now integrated into every engineer’s development flow. In this post, we’ll go through our phases of adopting Sorbet and the challenges and the lessons we learned along the way. We have been able to adopt Sorbet gradually while still benefiting from it on day one.</p><h3>Setting up</h3><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*8zktpC2f5ec53Nx5" /></figure><p>Setting up Sorbet was fairly easy: the adoption guides of <a href="https://sorbet.org/docs/adopting">Sorbet</a> and <a href="https://github.com/chanzuckerberg/sorbet-rails#initial-setup">sorbet-rails</a> left the codebase with 0 type errors. The <a href="https://sorbet.org/docs/metrics">type coverage metrics</a> were also promising: we got our codebase to about 80% files type-checked and 40% callsite-level typed coverage. It was a good start! However, it still left out important Rails models and libraries. Many files might not be type-checked (typed: false), or worse, <a href="https://github.com/chanzuckerberg/sorbet-rails#look-for--typed-ignore-files">ignored</a>.</p><p>We also disabled<strong> </strong>Sorbet’s <a href="https://sorbet.org/docs/runtime">runtime checks</a> initially. They are a key component of Sorbet to make sure method signatures are correct and match runtime behavior. However, they can cause errors in the production app if someone were to write an incorrect signature. At this stage, we only enabled them in RSpec tests to minimize its effects on the production system.</p><h3>Building a foundation</h3><p>Our next step was to develop an understanding of Sorbet and how it interacted with our system so we could develop a strategy to type-check our code. This also included figuring out what code is worth type-checking, and what could be left un-typed.</p><p>This was where we <strong>identified common code patterns</strong> and figured out how to make them type-checkable. This is important because when you figure out how to write these patterns with types, you enable people to <em>write new code </em>with types. This included core Rails abstractions like Model and Controller as well as abstractions and patterns that are created. Here’s a simplified example of a code pattern in our codebase:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4d9d5b776e1d576944b7425b96da61ed/href">https://medium.com/media/4d9d5b776e1d576944b7425b96da61ed/href</a></iframe><p>We made this pattern more friendly to type checking by changing the structure to let Sorbet validate the argument type automatically:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/3067734e0f6836d45012ec4efb52a240/href">https://medium.com/media/3067734e0f6836d45012ec4efb52a240/href</a></iframe><p>We also realized it would be important to have guardrails to ease people into adopting Sorbet. Here are a few integrations that we set up. They were invaluable in driving the adoption later:</p><ul><li><strong>Git integration</strong>: run type checks locally before creating or updating remote branches</li><li><strong>CI integration</strong>: run type checks automatically for each build</li><li><strong>CI integration</strong>: track metric changes after every commit merged to the master branch</li></ul><p>We found the adoption metrics important to understand how our adoption was going. On top of the metric Sorbet provided, We also found it useful to track individual contributions to type coverage and method signatures, because it tells you who is engaging with the tools and who may need more support. We recommend setting them up as early as possible!</p><h3>Ramping up type coverage</h3><p>Once the foundation was set, it was time to dive in and type our code! We started looking at our models and controllers and fixing type errors in them. It was <em>exciting</em> when we found a lot of dead-code or small bugs that wouldn’t be found without a tool like Sorbet!</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/741/1*cuK3StohabrYZythKpmK5Q.png" /><figcaption>We found many bugs and dead-code using Sorbet</figcaption></figure><p>We also faced many technical challenges in integrating Sorbet. We built <a href="https://github.com/chanzuckerberg/sorbet-rails">sorbet-rails</a> and documented a lot of <a href="https://github.com/chanzuckerberg/sorbet-rails#tips--tricks">tips &amp; tricks</a> about handling those challenges. Sometimes, we used T.unsafe to bypass type-checking on one or two lines of code so we could type-check the rest of a file. These were healthy compromises because our goal was not to blindly type-check everything, but instead to take advantage of type-checking when it is most useful.</p><p>We deemed these files important and set typed: true on all of them:</p><ul><li>All models</li><li>All controllers</li><li>All data mutation code</li><li>And all files enforcing our privacy controls!</li></ul><p>It doesn’t require a lot of effort to make files typed: true, because the requirement for typed: true is low — it only checks that the Ruby syntax is correct and methods exist. This drove up the file-level coverage to 90% and increased Sorbet’s surface area significantly. Once we made the files typed: true, it was also easier to ask other engineers to follow suit and use the same sigil in new files.</p><p>We also recruited engineers in the team as <strong>early adopters</strong>,<strong> </strong>who were eager and patient with initial hiccups. They were invaluable in providing insightful feedback about bugs and flagging issues that made Sorbet difficult to use. The latter was important: fixing code patterns that were hard to type-check enabled people to write type-checked code more easily, which was crucial in the next phase.</p><h3>Transitioning the team</h3><p>Our next goal was to make type-checking part of everyone’s development process. We ran a few <strong>training sessions</strong> to familiarize people with Sorbet and how to <em>write</em> type-checkable code. Following the training, we enabled type-checking in everyone’s development environments. At this phase, it was valuable to add <strong>non-blocking </strong><a href="https://en.wikipedia.org/wiki/Lint_(software)"><strong>lint rules</strong></a><strong> or checks</strong> to guide engineers in the team, for example:</p><p>Lint that new files must be typed: true (check out <a href="https://github.com/Shopify/rubocop-sorbet">rubocop-sorbet</a>)</p><ul><li>Lint that every pull request passes Sorbet type-checking.</li><li>Configure run-time checks to log in production. Errors are logged and reviewed without affecting production runtime.</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*OvyDjpY6LaD55BNH" /><figcaption>Our configuration was set to log errors in production, rather than raising them</figcaption></figure><p>It was important to make the rules non-blocking because we did not want people to see Sorbet as an obstacle for them to do their work. If they needed to make some changes quickly and didn’t have time to study the new tool yet, they should be able to skip over it. After 4 months, there were only 5 or 6 times when srb tc reported any error on our master branch.</p><p>We also <strong>celebrated people</strong> who contributed. We would give shout-outs to those who adopted type-checking early and contributed significantly to increasing the type-coverage on Slack and in our team meetings. Many adopters become advocates for Sorbet too: they found immediate benefits in using Sorbet and encouraged others to participate.</p><p>At this stage, the lift on engineers in the team was low, but the team increased the callsite-level type-coverage up 10% to 50%. We got there simply by writing code that doesn’t violate Sorbet type-checks and leveraging the signatures provided by Sorbet and `sorbet-rails`.</p><h3>Making it the norm</h3><p>By this point, we had all of our models, controllers, and new files typed: true. We gave people time to get used to running Sorbet type-checks and fixing type errors. It was time to speed up the adoption.</p><p>We upped the enforcement level of our lint checks:</p><ul><li>Required Sorbet type-checking to pass for the build to pass.</li><li>Piped run-time type errors to our error-reporting system, which directed them to responsible teams immediately.</li><li>Required that every <em>new</em> function is accompanied by a signature, again using the <a href="https://github.com/Shopify/rubocop-sorbet">rubocop-sorbet</a> gem.</li></ul><p>We started recruiting people to write signatures for existing code. One effective strategy was having new engineers type-check an old part of the codebase. It feeds two birds with one scone: they got to learn how the existing code worked, and the code got better type coverage. Sometimes, adding a few method signatures to a commonly used class or method (like ApplicationController) yielded a significant return in type-checking coverage.</p><p>These strategies accelerated the callsite-level typed coverage to 60% after about 2.5 months. Since then, callsite-level typed coverage in our codebase has steadily increased. People felt the benefits. At the same time, the amount of untyped code remained the same; there is still a lot of room to add types to existing code.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*RJxGRXJ0PvTxFBal" /></figure><p>One thing to note, we are still using non-blocking run-time checks in production. This makes people feel safe and comfortable writing method signatures. We don’t need them worried that they’ll break production if they make a small mistake like using String instead of Symbol in a method signature.</p><h3>Adoption challenges</h3><p>While our adoption has gone pretty well and has greatly improved our development process, it came with some challenges:</p><ul><li><strong>Type-checking existing code is hard and error-prone</strong>: When you change code, there is always a risk you’ll break it. This is why tools like “soft” runtime errors are crucial.</li><li><strong>Some code feels more verbose or clumsy</strong> than a Rubyist would like. We’re not talking about Sorbet sig — they are actually very easy to write and useful as documentation. We’re talking about programming constructs such as <a href="https://sorbet.org/docs/shapes">shapes</a> (a Hash with named keys) and enums (eg <a href="https://www.typescriptlang.org/docs/handbook/enums.html#string-enums">string enum</a> in Typescript). Sorbet offers alternatives using <a href="https://sorbet.org/docs/tstruct">T::Struct</a> and <a href="https://sorbet.org/docs/tenum">T::Enum</a>; however, they also make the code more verbose and harder to convert.</li><li><strong>Some patterns are very difficult to type</strong>, such as the DSL pattern used in RSpec or the method overloading pattern. This is due to various reasons, sometimes due to the dynamic nature of Ruby code makes it hard to capture in static typing, and sometimes due to the limitations of Sorbet as a tool. For the latter, Sorbet is being actively developed and I hope it will become more powerful with every version.</li></ul><h3>Lesson learned</h3><p>To adopt Sorbet quickly and smoothly, here’s what we learned:</p><ul><li>Focus on covering many files first, then drive the type-coverage within the file later.</li><li>Make sure common code patterns in the codebase are type-checkable.</li><li>Use non-blocking checks to guide people into adoption gradually.</li><li>It’s easy to write new code that is type-checked. Make it the default.</li><li>Type-checking existing code is an opportunity for new engineers to learn the codebase.</li><li>Celebrate along the way: bugs you find and fix, adoption progress, positive anecdotes. Sorbet is meant to be adopted gradually anyway!</li></ul><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/1*2XBU0--JIB7AcZ6D6cxTHQ.png" /><figcaption>Summary of the checks we have at each adoption stage</figcaption></figure><p>Sorbet is a great tool, and we hope that by sharing these lessons and the <a href="https://github.com/chanzuckerberg/sorbet-rails">tools</a> we developed, you will also adopt it successfully. We probably will never reach 100% type coverage, but that’s not the goal either. Some libraries do hacky, dynamic, untyped things to achieve awesomeness. But type-checking makes it easier and safer for our engineers to develop features, and our team is seeing the benefit of using Sorbet every step of the way.</p><p>Although there is still a lot to do, I’m optimistic our team will continue to move faster and ship more reliable code with Sorbet in our toolchain. We wouldn’t have been able to do it without incredible support and eagerness from the team. I’d like to express my gratitude to everyone on the CZI Education team!</p><h3>Additional resources</h3><p>You may read more about adopting sorbet in following resources:</p><ul><li><a href="https://sorbet.org/docs/adopting">Sorbet set-up guide</a></li><li><a href="https://sorbet.org/docs/metrics">Sorbet adoption tracking guide</a></li><li><a href="https://github.com/sorbet/sorbet/blob/master/docs/suggest-sig.md">Use Sorbet to find most “impactful methods” to type</a></li><li><a href="https://www.youtube.com/watch?v=v9oYeSZGkUw">Static Type Checking in Rails with Sorbet</a> by Hung Harry Doan</li><li><a href="https://blog.heroku.com/static-typing-ruby-with-sorbet">https://blog.heroku.com/static-typing-ruby-with-sorbet</a> by Heroku team</li><li><a href="https://shopify.engineering/static-typing-ruby">Static typing for Ruby</a> by Alexandre Terrasa (Shopify team)</li></ul><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=ff4e99296203" width="1" height="1" alt=""><hr><p><a href="https://medium.com/czi-technology/driving-adoption-of-sorbet-static-type-checking-in-rails-ff4e99296203">Driving adoption of Sorbet static type checking in Rails</a> was originally published in <a href="https://medium.com/czi-technology">CZI Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
        <item>
            <title><![CDATA[Static type checking in Rails with Sorbet]]></title>
            <link>https://medium.com/czi-technology/static-type-checking-in-rails-with-sorbet-dc0414a502d9?source=rss-da95afd45291------2</link>
            <guid isPermaLink="false">https://medium.com/p/dc0414a502d9</guid>
            <category><![CDATA[type]]></category>
            <category><![CDATA[sorbet]]></category>
            <category><![CDATA[type-checking]]></category>
            <category><![CDATA[ruby-on-rails]]></category>
            <category><![CDATA[rails]]></category>
            <dc:creator><![CDATA[Hung Doan]]></dc:creator>
            <pubDate>Tue, 03 Mar 2020 19:08:50 GMT</pubDate>
            <atom:updated>2020-03-05T02:37:06.094Z</atom:updated>
            <content:encoded><![CDATA[<p>At CZI, we developed a personalized learning application, the Summit Learning platform, using the Ruby on Rails framework. In the early days, Rails enabled us to build out the platform quickly. However, now that we have 30+ engineers and 2,500+ files of Ruby code written over 6 years, we’ve found it harder to iterate. To help us move faster together, we decided to adopt <a href="http://sorbet.org/">Sorbet</a>, a fast and powerful static type-checking tool for Ruby.</p><p>In this post series, we’d like to share our journey adopting Sorbet: the challenges and the lessons we learned from tackling those challenges. By reading these posts, you’ll learn the basics of using Sorbet to type-check an existing Rails app, and you’ll be equipped to drive the adoption of Sorbet on your team.</p><h3>WHAT IS SORBET?</h3><p><a href="http://sorbet.org/">Sorbet</a> is a Ruby static type checker developed by Stripe. Ruby is an interpreted language; objects and method calls are evaluated at run-time without any compilation step. If you attempt to call a nonexistent method on a Ruby object, Ruby cannot tell you in advance it’d be a problem. Instead, you’d get a NoMethodError when the code is executed:</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/51d56deff7349764a0cff54529a6cc4d/href">https://medium.com/media/51d56deff7349764a0cff54529a6cc4d/href</a></iframe><p>Statically typed languages like Java or C would be able to flag that this method doesn’t exist on an array. Sorbet brings this functionality to Ruby code: it can perform checks on code and flag this error without running the code. This process is referred to as static type checking.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/fcb32e0802262f44120c715a6fbcf03b/href">https://medium.com/media/fcb32e0802262f44120c715a6fbcf03b/href</a></iframe><p>Sorbet can bring a lot of good things to the developer experience: detect errors early, improve code quality, and sometimes flag dead code. To accomplish this, it relies on knowing object types and method signatures (sig) in the codebase. It already provides method signatures for Ruby’s core API, and users can define signatures for any custom method.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/0aae3ed6002d3a6fd3c9c2116acffad8/href">https://medium.com/media/0aae3ed6002d3a6fd3c9c2116acffad8/href</a></iframe><p>You probably can already foresee the challenge with adopting Sorbet at this point: will it have signatures for the framework and the gems that I use? Will I have to write signatures for all methods in my codebase? Worry not — Sorbet is meant to be adopted gradually. It can yield benefits with little adoption effort, but the more effort you put into it, the more value it will bring. Plus, we’ve already solved a lot of the challenges associated with adopting it in a Rails app.</p><h3>USING SORBET WITH RAILS</h3><p><a href="https://rubyonrails.org/">Ruby on Rails</a> poses many technical challenges to integrate static type checking. We’ve devised solutions for a number of these issues and open-sourced our solutions in <a href="https://github.com/chanzuckerberg/sorbet-rails">sorbet-rails</a>, a gem focusing on making the integration seamless.</p><p>The main challenge with type checking Rails code is that the framework relies a lot on <a href="https://en.wikipedia.org/wiki/Metaprogramming">meta-programming</a>, i.e. creating methods at run-time. For example, it is extremely simple to define an ORM (Object-Relational-Model) class in Rails, because the framework automatically generates a lot of functionality for the model.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8b95ae6e861fbcfdf3c1878a4a798eb9/href">https://medium.com/media/8b95ae6e861fbcfdf3c1878a4a798eb9/href</a></iframe><p>The use of meta-programming in Rails is very potent, as it helps engineers accomplish a lot with a few lines of code. However, because the methods are only added at run-time, it is a big challenge for a static type checker, which doesn’t run the code, to understand it. The static type checker doesn’t know about the existence of the methods, let alone knowing the methods’ signatures.</p><p>Sorbet provides a workaround for this problem: you can define method signatures for classes explicitly in <a href="https://sorbet.org/docs/rbi">Ruby Interface</a> files (RBI). RBI files only contain method definitions, not executable code.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/c9fd75595c6379169fde521d6b4f44b8/href">https://medium.com/media/c9fd75595c6379169fde521d6b4f44b8/href</a></iframe><p>After attempting to write the RBI file for our first model, we realized how big of a task it would be to write the RBI for all our models. There must be a way to solve this with code! We started trying to generate RBI files automatically, and this concept became the backbone of the sorbet-railslibrary.</p><h3>GENERATING RAILS RBIs</h3><p>sorbet-rails generates RBIs for Rails objects by inspecting the Rails environment at run-time. It does a few things:</p><ol><li>Detects generated methods (for each model or object),</li><li>Figures out their signatures, and</li><li>Writes the information to RBI files.</li></ol><p>You can think of it as creating a “cached” snapshot of proper signatures of the methods created at run-time. It can become outdated if you change the code without regenerating it. However, Sorbet now has the signatures at its disposal to do type checking quickly.</p><p>Rails provides a lot of <a href="https://en.wikipedia.org/wiki/Reflection_(computer_programming)">reflection methods</a>, e.g. <a href="https://www.rubydoc.info/docs/rails/4.1.7/ActiveRecord/Reflection/AssociationReflection">AssociationReflection</a>, that are invaluable for this process. However, there are generated methods for which Rails doesn’t provide enough information, like scopes or enum methods, and we have to find creative ways to collect the data needed. Currently, sorbet-rails can generate RBIs for a few different kinds of Rails objects: Models, Routes, and Mailers.</p><h4>Models</h4><p>Model RBI generation is the most fundamental but also most complex generation process in sorbet-rails. We generate methods for:</p><ul><li><strong>Model attributes</strong>: Based on database column definitions, we generate appropriate setters &amp; getters for each attribute. Rails provides an <a href="https://apidock.com/rails/ActiveRecord/Base/columns/class">easy accessor</a> to retrieve this information.</li><li><strong>Model associations</strong>: Similarly, Rails has extensive reflections on associations. Using this information, we can generate getters and setters for the associations.</li><li><strong>Querying methods</strong>: These methods are implemented once in ActiveRecord::Base, but in each subclass, they have a different return type. We generate them for each model to give them the correct return type.</li><li><strong>Scopes</strong>: Users can define “scope” to query a data collection in a model. Rails, however, doesn’t provide any reflection data for which scopes are defined in a model. We use the source_location of a method to determine whether they are scope methods. (Since they are generated methods, their “source_location” is the method that generates them).</li><li><strong>Enum</strong>: We overrode the enum method from Rails to collect <a href="https://api.rubyonrails.org/v5.2.4.1/classes/ActiveRecord/Enum.html">_prefixand </a><a href="https://api.rubyonrails.org/v5.2.4.1/classes/ActiveRecord/Enum.html">_suffix </a>options that are not provided by Rails reflections.</li></ul><p>Here is a snippet of the signatures sorbet-railswould generate. See our sample <a href="https://github.com/chanzuckerberg/sorbet-rails/blob/master/spec/test_data/v5.2/expected_wizard.rbi">RBI file</a> and how it works in a <a href="https://github.com/chanzuckerberg/sorbet-rails/blob/master/spec/generators/sorbet_test_cases.rb">type validation test</a>.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/4dcf76ec3360a37227179e0ab587c673/href">https://medium.com/media/4dcf76ec3360a37227179e0ab587c673/href</a></iframe><p>It’s common for Rails gems or privately defined modules to create additional methods in a model dynamically. sorbet-rails also provides a pluggable system that developers can hook into to generate signatures for them.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/966/0*FwhbxrMsWwsMONXn" /></figure><p>(Shout-out to <a href="https://github.com/AaronC81/parlour">Parlour</a> gem for handling the complexity of generating RBIs!)</p><p>Each plugin can add any number of method signatures to the RBI of a model. The generator will reconcile all the added methods and skip over any conflicts. This design gives developers full control of the generation process (yes, they can even swap out a core plugin).</p><p>sorbet-rails comes with <a href="https://github.com/chanzuckerberg/sorbet-rails/tree/master/lib/sorbet-rails/gem_plugins">plugins</a> for a few public gems, such as <a href="https://github.com/shrinerb/shrine/">Shrine</a>, <a href="https://github.com/elastic/elasticsearch">ElasticSearch</a>, and <a href="https://github.com/kaminari/kaminari">Kaminari</a>. We welcome contributions for more gem plugins!</p><h4>Routes</h4><p>sorbet-rails generates signatures for the <a href="https://guides.rubyonrails.org/routing.html#generating-paths-and-urls-from-code">path and URL methods</a> for all routes defined in a routes.rb. They are very handy for type-checking code in your controllers. For example, assuming there is a route named test_index, we would generate the following signatures.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/f35c11134ca0d0d508a2841daa0b17cc/href">https://medium.com/media/f35c11134ca0d0d508a2841daa0b17cc/href</a></iframe><h4>Mailers</h4><p><a href="https://guides.rubyonrails.org/action_mailer_basics.html#edit-the-mailer">Mailers</a> pose an interesting challenge for generating good RBIs. In a Rails mailer, you define an instance method, and Rails will generate a <em>class</em> method with matching parameters. Other developers interact with the mailer using the class method, not the instance method. When you write the Sorbet signature for a mailer method, sorbet-rails will create a signature for the class method based on the written signature — by retrieving the signature definition from Sorbet.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/8428ff3b71ec0459277fcb87610726bd/href">https://medium.com/media/8428ff3b71ec0459277fcb87610726bd/href</a></iframe><h3>OTHER FEATURES</h3><p>Generating RBIs simplifies the task of type checking Rails code. But it isn’t the end of the story. We also provide other features to make the task of adopting Sorbet seamless.</p><ol><li>Enabling the use of ::ActiveRecord_Relation in Sorbet signatures</li></ol><p>What we haven’t mentioned is that Relation classes like Wizard::ActiveRecord_Relation aren’t available to use in Sorbet signatures. It’s a private constant generated by Rails, and if you use it, you’ll be greeted with “Accessing private constant” error. We added a function to automatically make the Relation class of any model visible so that they can be used for type-checking!</p><p>2. Adding type to controller action params or external responses</p><p>The params of controller actions are input from users. They can have any type, and Sorbet normally cannot type check them. We added TypedParams as a way to specify the structure and the type of each parameter. They have an added benefit: now we’ve documented the parameters needed for a controller action! This technique is also useful when dealing with response data from external services.</p><iframe src="" width="0" height="0" frameborder="0" scrolling="no"><a href="https://medium.com/media/64f2202ee14e4e22efd2c1daa866ce43/href">https://medium.com/media/64f2202ee14e4e22efd2c1daa866ce43/href</a></iframe><p>There are also many <a href="https://github.com/chanzuckerberg/sorbet-rails#tips--tricks">tips &amp; tricks</a> we documented that are useful for type-checking your Rails app.</p><h3>RESULTS</h3><p>sorbet-rails has enabled us to type-check a lot of our code without writing any method signatures manually. Just setting up sorbet &amp; sorbet-railsgems, we were able to type check <strong>80% of our files</strong> and <strong>40% of the code</strong> in them. Our engineers reaped the benefit of improved productivity from type checking from day 1, as Sorbet has flagged numerous issues that manual review would have failed to catch.</p><figure><img alt="" src="https://cdn-images-1.medium.com/max/1024/0*CezeuZZgLWPUEuPN" /><figcaption>(the correct method name is `current_academic_year`)</figcaption></figure><p>As a fun exercise, I removed sorbet-rails from our codebase and compared how much of a difference it makes. When added, sorbet-rails reduced the number of untyped files by half and increased the type check scope of Sorbet significantly. It also doubled the number of <a href="https://sorbet.org/docs/metrics#call-site-level-typedness">call sites</a> that Sorbet can type check.</p><figure><img alt="" src="https://cdn-images-1.medium.com/proxy/0*h0Fxwz6ZYA09n89k" /><figcaption>Our type-check coverage with &amp; without sorbet-rails</figcaption></figure><p>The library has been received well by the community as well. We’ve seen adoption from many companies, such as Kickstarter and <a href="https://blog.heroku.com/static-typing-ruby-with-sorbet#exposing-columns-that-allowed-null-values">Heroku</a>. The gem is also <a href="https://sorbet.org/docs/metaprogramming-plugins">endorsed</a> by the Sorbet team as the library to type-check Rails code.</p><p>There is also a vibrant community using sorbet-rails: the project has been starred 300+ times, with 20+ public contributors who contributed ~70 commits (25% of the commits of the library!). I’d like to give special shout-outs for our <a href="https://github.com/chanzuckerberg/sorbet-rails/graphs/contributors">awesome contributors</a>, especially Connor Shea, Patrick Elis, and Alex Ghihecules. Without them, we wouldn’t have gone this far.</p><p>I’d like to thank the Sorbet team for the awesome tool that they created, and for listening to our feedback and collaborating with us to make the adoption successful!</p><p>If you’re interested in integrating Sorbet into your codebase, please look out for our next post on driving the adoption at the team level, what worked well and what didn’t.</p><h3>OPEN CHALLENGES</h3><p>While we’ve made Rails code a lot easier to type check, we’re not done yet. There are a number of technical challenges that we haven’t solved:</p><ul><li><strong>Mailer</strong>: Methods with default values. Currently, we cannot generate a signature with a default value.</li><li><strong>ActiveJob</strong>: There are things we can do to make type-checking jobs easier, but we haven’t gotten there yet.</li><li><strong>Refresh RBIs automatically</strong>: The RBI files can be out of date. We would like to automatically detect changes and update RBI files automatically.</li></ul><p>Sorbet is also a nascent project, and there are also features that Sorbet does not support that makes it hard to type check Rails code. Following are some key limitations we found:</p><ul><li><strong>Method overloading</strong>: Sorbet doesn’t support <a href="https://github.com/chanzuckerberg/sorbet-rails/issues/18#issuecomment-504500428">multiple signatures</a> for a single method, but it is a very common practice in Rails.</li><li><strong>Blocks</strong>: Type-checking blocks is challenging because a block can be executed in any context. It is difficult to type check configuration blocks like <a href="https://guides.rubyonrails.org/association_basics.html#association-extensions">association extensions</a><strong>.</strong></li><li><strong>Shape</strong>: Support for <a href="https://sorbet.org/docs/shapes">shape</a> is also limited. While it’s feasible to use T::Struct, it requires making a lot of code changes to type check code that uses a shape.</li></ul><p>If you would like to solve these challenges, please feel free to contribute to Sorbet and the <a href="https://github.com/chanzuckerberg/sorbet-rails">sorbet-rails</a> project! We’re actively developing and managing this library.</p><img src="https://medium.com/_/stat?event=post.clientViewed&referrerSource=full_rss&postId=dc0414a502d9" width="1" height="1" alt=""><hr><p><a href="https://medium.com/czi-technology/static-type-checking-in-rails-with-sorbet-dc0414a502d9">Static type checking in Rails with Sorbet</a> was originally published in <a href="https://medium.com/czi-technology">CZI Technology</a> on Medium, where people are continuing the conversation by highlighting and responding to this story.</p>]]></content:encoded>
        </item>
    </channel>
</rss>