Skip to main content
Published in Engineering Insights

Gnarly Learnings from January 2023

Gnarly Learnings from January 2023
Table of contents
  1. bin/rails notes
    1. How do you add custom tags to bin/rails notes?
  2. console.dir()
    1. Where does the console.dir depth option apply?
  3. Embedded Web Apps in Elixir with LiveState
    1. How is LiveState different from LiveView?
  4. Rails 7.1 Raises on Assignment to Readonly Attributes
    1. What are Rails readonly attributes?
    2. Does Rails 7.1 raise on readonly attributes by default?
    3. Which Active Record methods check readonly attributes?
    4. How do you make a model attribute read only?
    5. How is attr_readonly different from a readonly record?
  5. jsx-transform
    1. Does React 19 need the new JSX setup, and which tools support it?
  6. Storybook Ecosystem CI
    1. What does Storybook's CI system test?
  7. Contributors:

This January 2023 roundup of six topics is for Rails, JavaScript and Elixir developers. It covers what readonly attributes are, which Active Record methods check them and when Rails 7.1 raises. It also covers custom tags for bin/rails notes, the options of console.dir(), LiveState and LiveView, the new JSX setup, and what Storybook's CI system tests.

We love reading, watching, and listening in order to keep our skills sharp and our perspectives fresh. Here are some of the resources we learned from this month.

bin/rails notes#

Code comments are a pretty controversial topic but if you're a rails developer and you're in favor of them you should definitely check out bin/rails notes. Which allows you to search through your code comments for specific keywords. There are a few boilerplate keywords (also called annotations) that rails will look for by default (FIXME, OPTIMIZE, and TODO) but you can add custom annotations too. What's really great about this is that it could be used to set expectations and create a style guide for code comments so that the structure is consistent and the comments will always be easy to find.

How do you add custom tags to bin/rails notes?#

You add custom tags to bin/rails notes with config.annotations.register_tags, or pass them for a single run with the annotations option, per the Rails command line guide. The same guide gives config.annotations.register_directories for more folders and config.annotations.register_extensions for more file types. Those settings are how this roundup's "you can add custom annotations too" works. The guide's words for each one:

SettingThe guide's words
Annotations option"You can pass specific annotations by using the -a (or --annotations) option." Also: "Note that annotations are case sensitive."
register_tags"You can add more default tags to search for"
register_directories"You can add more default directories to search from"
register_extensions"You can add more default file extensions"

Without those settings, the guide says the command "will search in app, config, db, lib, and test directories" in "files with extension .builder, .rb, .rake, .yml, .yaml, .ruby, .css, .js, and .erb". As general advice, since the guide says annotations are case sensitive, a team that registers a custom tag should agree on one spelling.

console.dir()#

The developer consoles of modern browsers are incredibly feature-rich. One of the tools we learned about this month in the Chrome developer console is console.dir(). In the Chrome console, it shows an object as an expandable list of its properties, with disclosure triangles that open its child objects. In terminal runtimes like Node and Deno, you can pass it an object and a depth of null to print every level. 🤩Bonus tip! You can right-click an object (in the Chrome developer console), and click "copy object". This will allow you to grab the data and paste it somewhere for inspection in a nicely formatted way. You can also right-click the object and select "store object as global variable" and it will save the object in a variable that is available in the console.

Where does the console.dir depth option apply?#

The depth option works in terminal runtimes like Node and Deno, according to MDN. There, this roundup's tip to "pass it an object and a depth of null" prints every level. The MDN console.dir() page says: "In runtimes like Node and Deno, where console output goes to the terminal and is therefore not interactive, the options parameter provides a way to customize the way the object is presented." The table quotes the Node.js console docs and MDN's options list:

SourceWhat its docs say
Node.js"To make it recurse indefinitely, pass null. Default: 2."
MDN's options list"The value null means: print all levels. Defaults to 2."

Embedded Web Apps in Elixir with LiveState#

If you've ever had to embed third-party content into a web application, chances are you did it with an iframe. The frustrating thing with this approach is that you have no control over how the iframe displays, which complicates responsive layouts and disrupts the user experience. The LiveState library allows Elixir developers to manage state for embedded content, leaving some or all of the front-end implementation details up to the consuming application. That seems like a really flexible and attractive solution for anyone looking to ship a widget to their customers. Check out this example of an embeddable comments section to learn more.

How is LiveState different from LiveView?#

The LiveState README on HexDocs (version 0.9.0) says LiveView "entirely manages the web client side of the application", while "LiveState relies on client code to render state and dispatch events". Both keep event handlers in Elixir: the README says LiveState event handlers "are quite similar to LiveView event handlers".

LibraryThe README's words
LiveView"allows the user to write all of the application code, both server logic and view presentation logic, in Elixir"
LiveState"This trade-off keeps client side code simple, but allows LiveState to be used to build applications that are not as good of a fit for LiveView."

Under "Related projects", the README lists these front end packages:

  • phx-live-state: "The front end library npm package that implements sending and receiving events, and subscribing to state changes."
  • live-templates: "allows you to connect a front end template to a LiveState channel"
  • use-live-state: "A react hook for LiveState."

This roundup's comments example on launchscout.com now returns a 404 page. The Internet Archive copy holds Chris Nelson's post of August 5, 2022, "Building an Embeddable Web App with LiveState, Elixir, and Lit". It says, "For an embeddable web app, LiveView is no longer a viable option." It names the pattern LiveState extends: "properties down, events up." The linked talk is Chris Nelson's "Embedded Web Apps in Elixir with LiveState" at ElixirConf 2022, per its YouTube title. As general advice, LiveState suits a UI that must live inside a page you do not control, and LiveView suits a page Elixir serves whole.

Rails 7.1 Raises on Assignment to Readonly Attributes#

In Rails >=7.1 with the 7.1 defaults, assigning a new value to a readonly attribute on a saved record will raise an error. This feature is great because it prevents quiet failures that could cause issues with data integrity. If your app is on Rails >=7.1 with config.load_defaults below 7.1, you can opt in by heading over to your application.rb file and setting config.active_record.raise_on_assign_to_attr_readonly to true.

What are Rails readonly attributes?#

Rails readonly attributes are the attributes a model lists with attr_readonly, which the Rails API docs say "will be used to create a new record". The same page says, "Assigning a new value to a readonly attribute on a persisted record raises an error," and its Post example names that error ActiveRecord::ReadonlyAttributeError. Under the 7.1 defaults, that is the error this roundup's readonly item describes. The API pages for each name:

NameThe Rails API docs' words
attr_readonly"Attributes listed as readonly will be used to create a new record."
readonly_attributes"Returns an array of all the attributes that have been specified as readonly."
The option set to false"it will not raise. The value will change in memory, but will not be persisted on save."

The API page's own example:

class Post < ActiveRecord::Base
  attr_readonly :title
end

post = Post.create!(title: "Introducing Ruby on Rails!")
post.title = "a different title" # raises ActiveRecord::ReadonlyAttributeError
post.update(title: "a different title") # raises ActiveRecord::ReadonlyAttributeError

Before Rails 7.1, the Rails 7.0 API docs said: "You can assign a new value to a readonly attribute, but it will be ignored when the record is updated."

Does Rails 7.1 raise on readonly attributes by default?#

Rails 7.1 raises by default when the app loads the 7.1 defaults. The Configuring Rails guide lists config.active_record.raise_on_assign_to_attr_readonly as false in its "(original)" row and true starting with version 7.1. Kiprosh's linked article says "In a newly created Rails 7.1 application, config.load_defaults 7.1 is set by default in application.rb." It adds that the default "for config.load_defaults < 7.1 it is false". An app on Rails 7.1 or later with older defaults opts in through the step this roundup gives, "heading over to your application.rb file". The guide describes the old behavior this way: "The previous behavior would allow assignment but silently not persist changes to the database."

The dates, from the primary records:

Which Active Record methods check readonly attributes?#

The Active Record Persistence API docs name update_attribute and update_columns as methods that raise ActiveRecord::ActiveRecordError for a readonly attribute. For save and save!, the same page says "Attributes marked as readonly are silently ignored if the record is being updated." Without the 7.1 default, save skips the change quietly. Gnar's post ActiveRecord Cannot Read Minds warns about that kind of assumption. Its TL;DR says, "It can be dangerous to assume what those abstractions produce." With the 7.1 default on, the attr_readonly docs show the assignment itself raising, before any save. As general advice, once that default is on, a write to a readonly column that used to be silently skipped raises an error instead, so a test that runs that write will catch it. This roundup's line on that raise says "it prevents quiet failures that could cause issues with data integrity".

MethodThe Persistence docs' words
update_attribute"This method raises an ActiveRecord::ActiveRecordError if the attribute is marked as readonly."
update_column"Equivalent to update_columns(name => value)."
update_columns"This method raises an ActiveRecord::ActiveRecordError when called on new objects, or when at least one of the attributes is marked as readonly."

How do you make a model attribute read only?#

You make a model attribute read only by listing it with attr_readonly in the model class. The Rails guide Sign Up and Settings does this for an admin flag "for added security": "We can add attr_readonly in our model to protect the attribute from updates." The guide says the attribute "can still be set when creating a record", and it shows the way around the lock: "When admin is read-only, we have to directly update this in the database instead of using Active Record." As general advice, keep attr_readonly for columns no normal user flow should change, such as that admin flag, because every later change then means a direct database update.

How is attr_readonly different from a readonly record?#

attr_readonly covers named attributes of a persisted record, and a readonly record is blocked from being written: the Rails API docs for readonly! say it "Prevents records from being written to the database". The Active Record Querying guide says the readonly method on a relation will "explicitly disallow modification of any of the returned records". This roundup's item title, "Rails 7.1 Raises on Assignment to Readonly Attributes", covers the first kind. What the docs say about readonly records:

Readonly recordThe docs' words
In memory"Please, note that the objects themselves are still mutable in memory"
readonly?"Returns true if the record is read only."
On a relation"Any attempt to alter a readonly record will not succeed, raising an ActiveRecord::ReadOnlyRecord exception."
The error"Raised on attempt to update record that is instantiated as read only."

The first two rows come from the Rails API docs for readonly! and readonly?, the third from the Querying guide and the fourth from the ReadOnlyRecord API page.

jsx-transform#

React 17 includes a new version of the JSX transform which no longer requires importing React into modules. While this may not be an Earth-shattering increase in productivity, the story behind it is pretty interesting. React's old JSX transform used to compile down to using React.createElement behind the scenes, whereas the new JSX transform uses its own special functions. Depending on your setup, its compiled output may slightly improve the bundle size, on top of eliminating the need for the React import. It's also very easy to begin applying in an existing app. Just be sure to tell ESLint that the imports are no longer needed by setting react/react-in-jsx-scope to "off" in your configuration.

Does React 19 need the new JSX setup, and which tools support it?#

React 19 needs it. The React team's post of September 22, 2020 lists Create React App 4.0.0, Next.js v9.5.3, Gatsby v2.24.5, Babel v7.9.0, TypeScript v4.1 and Flow v0.126.0 as the first tool versions. It lists support in React 17 RC and higher, and in React 16.14.0, 15.7.0 and 0.14.10. The eslint-plugin-react docs for react-in-jsx-scope say the automatic JSX setup "is mandatory in React 19", and "When React >= 19.0.0 is detected, this rule is automatically disabled." If you use the new JSX setup from React 17, the plugin docs say to disable the rule by extending react/jsx-runtime: add "plugin:react/jsx-runtime" to "extends". This roundup gives the same step in one line: "Just be sure to tell ESLint that the imports are no longer needed by setting react/react-in-jsx-scope to "off" in your configuration." The versions, as the React post gives them:

ToolFirst version, per the React post
React"React 17 RC and higher supports it", plus "React 16.14.0, React 15.7.0, and React 0.14.10"
Create React App"4.0.0+"
Next.js"v9.5.3+"
Gatsby"v2.24.5+"
Babel"v7.9.0 and above"
TypeScript"v4.1 and up"
Flow"v0.126.0 and up"

The same post offers a codemod, npx react-codemod update-react-imports, to "Remove all unused React imports". It also says of those imports: "It doesn’t hurt to keep them".

Storybook Ecosystem CI#

Storybook is a neat tool for developing components in isolation. This month, they released Storybook Ecosystem CI with the goal of improving the developer experience. The author of the linked post above says it best: "Upgrading npm packages can be a bit like crossing a minefield". The new platform is intended to be an early warning system for dependency issues so we can avoid said minefield. The features include a status/reporting page, tests that run on each commit, and a notification system.

What does Storybook's CI system test?#

Storybook's CI system tests Storybook against its own configuration matrix: Michael Shilman's post of January 10, 2023 says it works "by testing this configuration matrix continuously and catching issues early". For each configuration, the post says its sandbox script "installs Storybook like a user would, adds a suite of stories, and runs a series of tests (Chromatic snapshots, Storybook test-runner and Playwright e2e)". The post's matrix, in its words:

  • "10+ renderers: React, Vue, Angular, Web components, Svelte, Ember, HTML, and more"
  • "2 languages: JS, TS"
  • "2 builders: Webpack, Vite"
  • "3 package managers: npm, yarn, pnpm"
  • "Meta-frameworks like NextJS, SvelteKit, etc."

Alerts come from "a notification system that posts to the Storybook Discord whenever CI breaks". This roundup's line on why it matters: "The new platform is intended to be an early warning system for dependency issues so we can avoid said minefield."

Contributors:#

Learn more about how The Gnar builds software.

Frequently asked questions

How can I inspect an entire object in the console?

The post says that in the Chrome console, console.dir() shows an object as an expandable list of its properties, and that in Node and Deno a depth of null prints every level. It also describes copying an object or storing it as a global variable in the Chrome developer console.

What happens when I assign a readonly attribute in Rails 7.1?

The post says an assignment raises an error, preventing quiet failures. For Rails 7.1 or later apps that keep older framework defaults (config.load_defaults below 7.1), it says to turn that error on by setting raise_on_assign_to_attr_readonly to true under config.active_record in application.rb.

Does the new JSX transform require importing React?

The version included in React 17 no longer requires importing React into modules. The post also says to turn off react/react-in-jsx-scope in the ESLint configuration.

What are readonly attributes in Rails?

They are the attributes a model lists with attr_readonly. The Rails API docs say they "will be used to create a new record", and that "Assigning a new value to a readonly attribute on a persisted record raises an error." Under the Rails 7.1 defaults, the error class is ReadonlyAttributeError. With raise_on_assign_to_attr_readonly set to false, the docs say "it will not raise."

How do you change a readonly attribute in Rails?

Update it directly in the database instead of through Active Record. The Rails sign up and settings guide does this for its admin flag: "When admin is read-only, we have to directly update this in the database instead of using Active Record." Normal assignment and save will not save a change to a readonly attribute on a saved record.

What is the difference between a readonly attribute and a readonly record?

A readonly attribute covers the attributes named in attr_readonly, and a readonly record covers the whole record. The Rails API docs say readonly! "Prevents records from being written to the database". Their examples show save, update and destroy each raising ReadOnlyRecord on such a record.

What is the difference between LiveState and LiveView?

LiveState leaves rendering to client code. Its README says LiveView "entirely manages the web client side of the application", while "LiveState relies on client code to render state and dispatch events". It adds that LiveState event handlers "are quite similar to LiveView event handlers".

Does React 19 need the new JSX setup?

Yes. The eslint-plugin-react docs say the automatic JSX setup "is mandatory in React 19", and its rule asking for React in scope "is automatically disabled" when React 19 is detected. React 17 added the new setup, and the React team also released it for React 16.14.0, 15.7.0 and 0.14.10.

Where to go from here

  • Your US company does over $10M a year in revenue, and its order system is holding you back.

    Talk to Pete Whiting
  • You want AI to save your company money. With Compass, if we don't find at least $350,000 a year in savings, you don't pay.

    See how Compass works
  • Everyone else: get our newest posts by email.

    Get the newsletter

Stay In The Loop

Never miss an update. Get the latest blogs, webinars, and expert insights straight to your inbox from The Gnar.