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.
The Practical Effects on the GVL on Scaling in Ruby#
In "The Practical Effects of the GVL on Scaling in Ruby", Nate Berkopec provides a great practical overview of parallelism and concurrency, along with the challenges they pose to C-based interpreters. The post is a few years old-Ractors are now a reality-but the exposition is well worth a bit of mental fast-forwarding. Short version: We commonly separate tasks into those that are CPU-bound, spending most of their time executing instructions, and those that are I/O bound, spending most of their time waiting for data to be sent or received. In order to make the best use of the C-based Ruby interpreter, you need to assess where your job falls on this spectrum.
extend self in Ruby#
Modules are a great way to encapsulate logic that is shared between objects. But what if you want to use that logic directly (e.g. MyModule.my_method)? Turns out this is not callable unless it's defined as def self.my_method. Though doing this would mean other objects that extend MyModule would no longer be able to call that method; not what we want. If instead MyModule extends itself, #my_method becomes directly available on MyModule and remains available on any objects extending MyModule!
ActiveRecord Supports Postgres Enum Types#
Enums are great for hardening up validations. But reading integer values can be a little cryptic. One solution is to use Postgres's enum types in migrations. And now Rails 7 gives us a power-up with Postgres enumerated types baked into AR.
Web Almanac: JavaScript in 2022#
The Web Almanac, unlike the Farmer's Almanac, won't tell you when winter begins or how long after the last full moon in October you should plant your garlic, but it does provide insight into the state of the web. This section focuses specifically on JavaScript, its trends, and usages but there are other goodies in the almanac too. Definitely take the time to check out the other sections on CSS, UX, markup, and more!
redirect_back_or_to#
Sometimes, we don't know exactly where we want to go or how we want to get there. For times like these, we can reach for handy methods like redirect_back_or_to. By default, the browser will be redirected back to the referrer. The referrer is determined via a request header (HTTP Referer (sic)), which isn't always available because it is based on browser security settings and user preferences. But even in the event that the header is missing, it's all gravy because we can provide a fallback location to redirect to instead!
Data.define#
In Ruby 3.2 a simple, native value object will be added to Ruby as a core class. Hello, Data. While I am not particularly thrilled about the name I am excited about the implementation, as I have found myself frequently reaching for value objects. The define method will be used to initialize an instance of this class with either positional or keyword arguments. My first thought was that this class sounded eerily similar to a Struct. However, Structs are mutable, collection-like, and dictionary-like, where Data are not. The PR for this feature is linked in the title but you can check out the proposal for it here.
What does the GVL change when you scale a Ruby app?#
Puma is a Ruby web server, and Puma's README says that on MRI, "there is a Global VM Lock (GVL) that ensures only one thread can run Ruby code at a time." Threads in one process can still wait on IO in parallel. For CRuby on a machine with more than 1 CPU core, Puma's deployment guide says that in general you should use cluster mode, which runs more than one process. CRuby is the mainline Ruby implementation, written in C, and people sometimes call it MRI. A process is one running copy of your app, and a thread is one line of work inside it.
This post sorts jobs into CPU-bound work, which spends most of its time running instructions, and I/O-bound work, which spends most of its time waiting for data. It says "you need to assess where your job falls on this spectrum." Puma's documentation says what each setup allows. On the thread count, Puma's deployment guide says "Unless you have a very I/O-heavy application (50%+ time spent waiting on IO), use the default thread count (5 for MRI)."
| Setup | What the documentation says | Source |
|---|---|---|
| Several threads in one process, all running Ruby code | The GVL "ensures only one thread can run Ruby code at a time." | Puma README |
| Several threads in one process, waiting on blocking IO such as HTTP calls to external APIs | Puma allows "IO waiting to be done in parallel". | Puma README |
| More than one process, called cluster mode | Cluster mode forks workers from a master process. "Each child process still has its own thread pool." | Puma README |
| A Ruby with no GVL | Speedshop says the GVL "doesn’t exist in JRuby or TruffleRuby". Puma says "parallel Ruby implementations (TruffleRuby, JRuby) don't have this limitation." | Speedshop and Puma README |
A worker is one of those child processes. Puma's README says "the -t thread flag setting is per worker, so -w 2 -t 16:16 will spawn 32 threads in total, with 16 in each worker process." In that example, -w sets the number of workers and -t sets the threads.
Puma's own rule for choosing a mode#
- Puma's deployment guide says that in general you should use single mode only if you run JRuby, TruffleRuby or another fully multithreaded implementation of Ruby, or you run MRI where only 1 CPU core is available. Otherwise it says to use cluster mode to make use of all available CPU resources. Single mode means the worker count is 0, and any higher count runs cluster mode.
- In cluster mode, match the worker count to the number of CPU cores on the machine, with a minimum of 2, per the guide. With fewer than 2 CPU cores, the guide says to use single mode. The guide's workers :auto setting needs the concurrent-ruby gem, a packaged Ruby library. If you cannot add the gem, set the worker count by hand to the available CPU cores.
- Set the thread count to the desired number of concurrent requests divided by the number of workers.
The guide counts CPU cores as the physical cores on ARM. On x86 it counts logical cores, hyperthreads or vCPUs, which it says all mean the same thing.
Puma's README says cluster mode is not supported on Windows or on JRuby. The worker count and thread count steps apply where cluster mode is available.
What can a Postgres enum type do, and what can it not?#
A Postgres enum, short for enumerated type, is "a static, ordered set of values". You can add values to it and rename them. You cannot remove a value or change the sort order without dropping and re-creating the type.
Each value has a label, which is the text the value is shown as. This post says "reading integer values can be a little cryptic." The Gnar Company's post Enum Types in Postgres adds a warning about removal: "If you want to remove a value once it’s already been created, unfortunately you can’t do that."
| Question | What the documentation says | Source |
|---|---|---|
| How do I create one and use it? | Enum types are created with the CREATE TYPE command. "Once created, the enum type can be used in table and function definitions much like any other type." | PostgreSQL docs 8.7.1 |
| What order do the values have? | "The ordering of the values in an enum type is the order in which the values were listed when the type was created." Standard comparison operators and related aggregate functions are supported. | PostgreSQL docs 8.7.2 |
| Can I compare two different enum types? | "Each enumerated data type is separate and cannot be compared with other enumerated types." For that case the docs say you can write a custom operator or add explicit casts to your query. | PostgreSQL docs 8.7.3 |
| Are labels case sensitive? | "Enum labels are case sensitive, so 'happy' is not the same as 'HAPPY'." White space in the labels is significant too. | PostgreSQL docs 8.7.4 |
| How big is a value or a label? | "An enum value occupies four bytes on disk." In standard builds a label is at most 63 bytes. | PostgreSQL docs 8.7.4 |
| Can I add a value? | Yes. ADD VALUE can place the new value BEFORE or AFTER an existing value. Otherwise, "the new item is added at the end of the list of values." | PostgreSQL ALTER TYPE docs |
| Can I rename a value? | Yes. RENAME VALUE renames a value of an enum type, and "the value's place in the enum's ordering is not affected." | PostgreSQL ALTER TYPE docs |
| Can I remove a value or change the order? | "Existing values cannot be removed from an enum type, nor can the sort ordering of such values be changed, short of dropping and re-creating the enum type." | PostgreSQL docs 8.7.4 |
On the Rails side, the Rails Guides page Active Record and PostgreSQL says the type "can be mapped as a normal text column, or to an ActiveRecord::Enum". A migration is a Ruby file that changes the database structure. The Rails 7.0.0 changelog says "In migrations, use create_enum to add a new enum type, and t.enum to add a column." The same entry says "Enums will be presented correctly in schema.rb", the file where Rails records the database structure. It adds that this is only supported by the PostgreSQL adapter, the part of Active Record that talks to Postgres.
The Rails 7.1.0 changelog says it added PostgreSQL migration commands for enum rename, add value, and rename value, and a drop_enum command. The current Rails guide also says declaring an enum attribute in a model, which is the Ruby class for a database table, "adds helper methods and prevents invalid values from being assigned to instances of the class". It says its example migrations "are both reversible, but you can define separate #up and #down methods if required." It says to remove any columns or tables that depend on the enum type before dropping it. It says "Enum values can't be dropped, which also means add_enum_value is irreversible." To rename a value, it says you can use rename_enum_value.
What fallback and options does redirect_back_or_to take?#
In the Rails API's examples, the fallback location is a hash, a record, a URL string, a path string, a URL helper or a proc. The options are allow_other_host and any other option that redirect_to accepts. You pass the fallback location as the first argument to redirect_back_or_to, and an argument is a value you hand to a method. The Rails API says "If the request is missing this header, the fallback_location will be used." The header is the one that names the referrer, which is the page that sent the browser here, and it is spelled "Referer" (sic).
This post says "it's all gravy because we can provide a fallback location to redirect to instead." The Rails API says what that location can be and which options come with it.
| What you pass | What the Rails API says | Source |
|---|---|---|
| Fallback location, the first argument | The API's examples include a hash that names an action and an id, a record such as @post, a full URL string, a path string such as "/images/screenshot.jpg", a URL helper such as posts_url, and a proc, which is a stored block of Ruby code. | redirect_back_or_to |
| allow_ | It is documented as "Allow or disallow redirection to the host that is different to the current host". A host is the address of a site. One API example passes "/" as the fallback location and sets the option to false. In the source the API shows, Rails uses the referrer only when it is present and either this option is true or the referrer's host is allowed. Otherwise it redirects to the fallback location. | redirect_back_or_to |
| Any other option | "All other options that can be passed to redirect_to are accepted as options, and the behavior is identical." A redirect_to call sends a 302 Found unless the status option says otherwise, and "the status code must be a 3xx HTTP code, or redirection will not occur." It takes flash messages, which are short notes for the next page, through the alert and notice accessors or a general purpose flash bucket. | redirect_to |
| redirect_ | The API calls it a "Soft deprecated alias for redirect_back_or_to". An alias is a second name for the same method. Its fallback location is a keyword argument, which you pass by name. The newer method takes it as the first positional argument. | redirect_back |
A visitor can also arrive with no referrer at all. MDN says the Referrer-Policy header decides what is sent. With no-referrer, "The Referer header will be omitted: sent requests do not include any referrer information." With same-origin, the policy is "Don't send the Referer header for cross-origin requests."
MDN also says "The request's referrer policy defines the data that can be included." So a request that follows a link from another site can arrive without the header, and then Rails uses the fallback location.
Contributors:#
Learn more about how The Gnar builds software.


