Weeknotes 2041

Work

A lot of my work at the moment involves chasing down bugs in an incredibly complicated publishing system which has multiple triggers (both internal and external) that make films available to watch on a variety of platforms at specific times in specific countries. When bugs creep in, films either stay up or don’t go up, and sometimes that annoys the wrong people. This week was one of those weeks, but involving a bug that was introduced about two years ago, and then fixed 8 months later, so calculating the true impact of the issue is pretty difficult. This is definitely why I got into software development.

Not work

Does this site now run on Ruby 3.1? I hope it does. I’ve been slowly working through a bunch of my other small applications, trying to update them to modern versions of Ruby (and even Rails), so that at the very least they remain deployable. This site is one of those small applications.

My real job

As the parent of an infant, I am now accustomed to exhaustion, and within that broad label, all the subtly-distinct flavours it comes in. This week has mostly been standard not-enough-contiguous-hours-of-unconsciouness tiredness. Number of thousand-yard stares while the child does not immediately need my attention: 5.

Physical health

None of this is helped by having yet another cold of some kind. Which of course we all get, and so it’s a never ending cycle of minor illness and sleep distruption and nobody is feeling very jazzy or sparkly but at the same time, the kid is so damned adorable that it remains worth it.

Mental health

Some rare adult socialisation in the form of a birthday party for another child (but yes, it still counts), and then Tom & Nat coming over for lunch today, both of which were very excellent.

Door

Today I found a door in my hallway that I hadn’t noticed before, but I’m currently too tired to investigate further.

Connoisseur

Listen, here’s what I’m wondering: is it better to be able to appreciate subtle refinements and improvements of a thing, the finest examples of it, if it comes at the expense of enjoying the version of that thing that’s most commonly or easily available?

If that “better” thing gives an increase of happiness of X, but the more commonly available instances – in their relative worseness – now gives a decrease of happiness of Y, then how often is the sum of X greater than the sum of Y?

Is it better to really get into, say, wine, for all the increased enjoyment that those few really great wines can provide, if it means that you either need to spend a new multiple on acquiring that wine, or suffer increasing disappointment from the wines you can affort or are offered at friends houses?

Or is it better – on the whole – to remain largely ignorant of what distinguishes a “great” wine from an “ok” wine, and just enjoy them all to a lesser but more consistently positive extent?

It might not be wine, it could be chocolate, or coffee, or art, or pretty much anything else that you can develop a “taste” for. Are the newly-available highs of pleasure worth, overall, the lessened ability to tolerate the instances of that thing which do not match your new palate?

This is what I’m wondering. Sound out in the comments1

The only clue I can offer is that it’s a literal nightmare figuring out how to spell “connoisseur”. I had to look it up to write this. Twice.

The universe weaves clues into its ineffable fabric, I suppose.

  1. JK there are no comments here – literal LOL – nah, you go scream into whatever digital silo you prefer. 

This is for Patrick

This is for Patrick, who doesn’t subscribe to the RSS or Atom feeds.

Instead he sets a reminder to check this website every week or two (or perhaps less, I forget), and – upon seeing no new posts – sets another reminder to do the same later that month, or year, or whenever.

This is for Patrick, who has lost so many precious seconds checking this site for new posts, only to find nothing.

I won’t be responsible for this anymore. I won’t burn his time and energy like electron potential on the bitcoin bonfire. I won’t be the source of that disappointment. My stale blog-type thing won’t be the reflection in that lone tear as it traces its melancholy path down his face. Not anymore.

This post, Patrick… buddy… this is for you.

Don't cache ActiveRecord objects

Hello, new Rails developer! Welcome to WidgetCorp. I hope you enjoyed orientation. Those old corporate videos are a hoot, right? Still, you gotta sit through it, we all did. But anyway, let’s get stuck in.

So as you know, here at WidgetCorp, we are the manufacturer, distributor and direct seller of the worlds highest quality Widgets. None finer!

These widgets are high-value items, it’s a great market to be in, but they’re also pretty complicated, and need to be assembled from any number of different combinations of doo-hickeys, thingamabobs and whatsits, and unless we have the right quantities and types of each, then a particular kind of widget may not actually be available for sale.

(If you just came for the advice, you can skip this nonsense.)

But those are manufacturing details, and you’re a Rails developer, so all it really means for us is this: figuring out the set of available widgets involves some necessarily-slow querying and calculations, and there’s no way around it.

In our typical Rails app, here’s the code we have relating to showing availble widgets:

# db/schema.rb
create_table :widgets do |t|
  t.string :title
  # ...
end

# app/models/widget.rb
class Widget < ActiveRecord::Base
  scope :available, -> { 
    # some logic that takes a while to run
  }
end

# app/helpers/widget_helper.rb
module WidgetHelper
  def available_widgets
    Widget.available
  end
end
<!-- app/views/widgets/index.html.erb -->
<% available_widgets.each do |widget| %>
  <h2><%= widget.name %></h2>
  <%= link_to 'Buy this widget', widget_purchase_path(widget) %>
<% end %>

It’s so slow!

The complication of these widgets isn’t our customer’s concern, and we don’t want them to have to wait for even a second before showing them the set of available widgets that might satisfy their widget-buying needs. But the great news is that the widget component factory only runs at midnight, and does all its work instantaneously1, so this set is the same for the whole day.

So what can we do to avoid having to calculate this set of available widgets every time we want to show the listing to the user, or indeed use that set of widgets anywhere else in the app?

You guessed it, you clever Rails developer: we can cache the set of widgets!

For the purposes of this example, let’s add the caching in the helper:2

module WidgetHelper
  def available_widgets
    Rails.cache.fetch("available-widgets", expires_at: Date.tomorrow.beginning_of_day) do
      Widget.available
    end
  end
end

Bazinga! Our website is now faster than a ZipWidget, which – believe me – is one of the fastest widgets that we here at WidgetCorp sell, and that’s saying something.

Anyway, great work, and I’ll see you tomorrow.

The next day

Welcome back! I hope you enjoyed first night in the company dorm! Sure, it’s cosy, but we find that the reduced commute times helps us maximise employee efficiency, and just like they said in those videos, say it with me: “An efficient employee is… a…”

… more impactful component in the overall WidgetCorp P&L, that’s right. But listen to me, wasting precious developer seconds. Let’s get to work.

So corporate have said they want to store the colour of the widget, because it turns out that some of our customers want to coordinate their widgets, uh, aesthetically I suppose. Anyway, I don’t ask questions, but it seems pretty simple, so let’s add ourselves the column to the database and show it on the widget listing:

# db/schema.rb
create_table :widgets do |t|
  t.string :title
  t.string :colour
  # ...
end
<!-- app/views/widgets/index.html.erb -->
<% available_widgets.each do |widget| %>
  <h2><%= widget.title %></h2>
  <p>This is a <%= widget.colour %> widget</p>
  <!-- ...  -->
<% end %>

… aaaaaaaand deploy.

Great! You are a credit to the compa WHOA hangon. The site is down. THE SITE IS DOWN.

Exceptions. Exceptions are pouring in.

“Undefined method colour”? What? We ran the migrations right? I’m sure we did. I saw it happen. Look here, I’m running it in the console, the attribute is there. What’s going on? Oh no, the red phone is ringing. You answer it. No, I’m telling you, you answer it.

What’s going on

The reason we see exceptions after the deployment above is that the ActiveRecord objects in our cache are fully-marshalled ruby objects, and due to the way ActiveRecord dynamically defines attribute access, those objects only know about the columns and attributes of the Widget class at the time they entered the cache.

And so here’s the point of this silly story: never store objects in your cache whose structure may change over time. And in a nutshell, that’s pretty much any non-value object:

Marshalling data

If you take a look at how Rails caching actually works, you can see that under the hood, the data to be cached is passed to Marshal.dump, which turns that data into an encoded string.

We can see what that looks like here:

$ widget = Widget.create(title: 'ZipWidget')
$ data = Marshal.dump(widget)
# \x04\bo:\vWidget\x16:\x10@new_recordF:\x10@attributeso:\x1EActiveModel::AttributeSet\x06;
# \a{\aI\"\aid\x06:\x06ETo:)ActiveModel::Attribute::FromDatabase\n:\n@name@\b:\x1C
# @value_before_type_casti\x06:\n@typeo:\x1FActiveModel::Type::Integer\t:\x0F@precision0
# :\v@scale0:\v@limiti\r:\v@rangeo:\nRange\b:\texclT:\nbeginl-\t\x00\x00\x00\x00\x00\x00\x00\x80:\b
# endl+\t\x00\x00\x00\x00\x00\x00\x00\x80:\x18@original_attribute0:\v@valuei\x06I\"\ntitle\x06;
# \tTo;\n\n;\v@\x0E;\fI\"\x0EZipWidget\x06;\tT;\ro:HActiveRecord::ConnectionAdapters::AbstractMysqlAdapter::MysqlString\b;
# \x0F0;\x100;\x11i\x01\xFF;\x170;\x18I\"\x0EZipWidget\x06;\tT:\x17@association_cache{\x00:\x11
# @primary_keyI\"\aid\x06;\tT:\x0E@readonlyF:\x0F@destroyedF:\x1C@marked_for_destructionF:\x1E
# @destroyed_by_association0:\x1E@_start_transaction_state0:\x17@transaction_state0:\x17
# @inspection_filtero:#ActiveSupport::ParameterFilter\a:\r@filters[\x00:\n@maskU:
# 'ActiveRecord::Core::InspectionMask[\t:\v__v2__[\x00[\x00I\"\x0F[FILTERED]\x06;\tT:$
# @_new_record_before_last_commitT:\x18@validation_context0:\f@errorsU:\x18
# ActiveModel::Errors[\b@\x00{\x00{\x00:\x13@_touch_recordT:\x1D@mutations_from_database0: 
# @mutations_before_last_saveo:*ActiveModel::AttributeMutationTracker\a;\ao;\b\x06;\a{\a
# @\bo:%ActiveModel::Attribute::FromUser\n;\v@\b;\fi\x06;\r@\n;\x17o;\n\n;\v@\b;\f0;\r
# @\n;\x170;\x180;\x18i\x06@\x0Eo;0\n;\v@\x0E;\fI\"\x0EZipWidget\x06;\tT;\r@\x11;\x17o;\n\t;
# \v@\x0E;\f0;\r@\x11;\x170;\x18@\x10:\x14@forced_changeso:\bSet\x06:\n@hash}\x00F

If you look closely in there, you can see some of the values (e.g. the value ZipWidget), but there’s plenty of other information about the specific structure and implementation of the ActiveRecord instance – particularly about the model’s understanding of the database – that’s encoded into that dump.

You can revive the object by using Marshal.load:

$ cached_widget = Marshal.load(data)
# => #<Widget id: 1, title: "ZipWidget">

And that works great, until you try and use any new attributes that might exist in the database. Let’s add the colour column, just using the console for convenience:

$ ActiveRecord::Migration.add_column :widgets, :colour, :string, default: 'beige'

We can check this all works and that our widget in the database gets the right value:

$ Widget.first.colour
# => 'beige'

But what if we try and use that same widget, but from the cache:

$ cached_widget = Marshal.load(data)
# => #<Widget id: 1, title: "ZipWidget">
$ cached_widget.colour
Traceback (most recent call last):
        1: from (irb):14
NoMethodError (undefined method `colour' for #<Widget id: 1, title: "ZipWidget">)

Boom. The cached instance thinks it already knows everything about the schema that’s relevant, so when we try to invoke a method from a schema change, we get an error.

Workarounds

The only ways to fix this are

Not great.

But there’s a better solution, which is avoiding this issue in the first place.

Store IDs, not objects

Sometimes it is useful to take a step back from the code and think about what we are trying to acheive. We want to quickly return the set of available widgets, but calculating that set takes a long time. However, there’s a difference between calculating the set, and loading that set from the database. Once we know which objects are a part of the set, actually loading those records is likely to be pretty fast – databases are pretty good at those kinds of queries.

So we don’t actually need to cache the fully loaded objects; we just need to cache something that lets us quickly load the right objects – their unique ids.

Here’s my proposed fix for WidgetCorp:

module WidgetHelper
  def available_widgets
    ids = Rails.cache.fetch('available-widgets', expires_at: Date.tomorrow.beginning_of_day) do
      Widget.available.pluck(:id)
    end
    Widget.where(ids: ids)
  end
end

Yes, it’s less elegant that neatly wrapping the slow code in a cache block, but the alternative is a world of brittle cache data and deployment fragility and pain. If a new column is added to the widgets table, nothing breaks because we’re not caching anything but the IDs.

Bonus code: defend your app from brittle cache objects

It can be easy to forget this when you’re building new features. This is the kind of thing that only bites in production, and it can happen years after the unfortunate cache entered use.

So the best way of making sure to avoid it, is to have something in your CI build that automatically checks for these kinds of records entering your cache.

In your config/environments/test.rb file, find the line that controls the cache store:

# config/environments/test.rb
config.cache_store = :null

and change it to this:

# config/environments/test.rb
config.cache_store = NullStoreVerifyingAcceptableData.new

And in lib, create this class:

# lib/null_store_verifying_acceptable_data.rb
class NullStoreVerifyingAcceptableData < ActiveSupport::Cache::NullStore
  class InvalidDataException < Exception; end

  private

  def write_entry(key, entry, **options)
    check_value(entry.value)
    true
  end

  def check_value(value)
    if value.is_a?(ActiveRecord::Base) || value.is_a?(ActiveRecord::Relation)
      raise InvalidDataException, 
        "Tried to store #{value.class} in a cache. We cannot do this because \
        the behaviour/schema may change between this value being stored, and \
        it being retrieved. Please store IDs instead."
    elsif value.is_a?(Array) || value.is_a?(Set)
      value.each { |v| check_value(v) }
    elsif value.is_a?(Hash)
      value.values.flatten.each { |v| check_value(v) }
    end
  end
end

With this in place, when your build runs any test that exercises behaviour that ends up trying to persist ActiveRecord objects into the cache will raise an exception, causing the test to fail with an explanatory message.

You can extend this to include other classes if you have other objects that may change their interface over time.

Double bonus: tests for NullStoreVerifyingAcceptableData

How can we be confident that the new cache store is actually going to warn us about behaviours in the test? What if it never ever raises the exception?

When I’m introducing non-trivial behaviour into my test suite, I like to test that too. So here’s some tests to sit alongside this new cache store, so we can be confident that we can actually rely on it.

require 'test_helper'

class NullStoreVerifyingAcceptableDataTest < ActiveSupport::TestCase
  setup do
    @typical_app_class = Widget
  end

  test 'raises exception when we try to cache an ActiveRecord object' do
    assert_raises_when_caching { @typical_app_class.first }
  end

  test 'raises an exception when we try to cache a relation' do
    assert_raises_when_caching { @typical_app_class.first(5) }
  end

  test 'raises an exception when we try to cache an array of ActiveRecord objects' do
    assert_raises_when_caching { [@typical_app_class.first] }
  end

  test 'raises an exception when we try to cache a Set of ActiveRecord objects' do
    assert_raises_when_caching { Set.new([@typical_app_class.first]) }
  end

  test 'raises an exception when we try to cache a Hash that contains ActiveRecord objects' do
    assert_raises_when_caching { {value: @typical_app_class.first} }
  end

  test 'does not raise anything when caching an ID' do
    Rails.cache.fetch(random_key) { @typical_app_class.first.id }
  end

  test 'does not raise anything when caching an array of IDs' do
    Rails.cache.fetch(random_key) { @typical_app_class.first(5).pluck(:id) }
  end

  private

  def assert_raises_when_caching(&block)
    assert_raises NullStoreVerifyingAcceptableData::InvalidDataException do
      Rails.cache.fetch(random_key, &block)
    end
  end

  def random_key
    SecureRandom.hex(8)
  end
end

If you extend the cache validator to check for other types of objects, you can add tests to make sure those changes work as you expect.

Triple-bonus code: what if you already have cached objects?

My real fix for WidgetCorp would actually try to mitigate this issue while still respecting the (possibly broken) objects still in the cache:

module WidgetHelper
  def available_widgets
    ids_or_objects = Rails.cache.fetch('available-widets', expires_at: Date.tomorrow.beginning_of_day) do
      Widget.available.pluck(:id)
    end
    ids = if ids_or_objects.first.present? && ids_or_objects.first.is_a?(ActiveRecord::Base) 
      ids_or_objects.map(&:id)
    else
      ids_or_objects
    end
    Widget.where(id: ids)
  end 
end

This allows us to still use the ActiveRecord instances that are cached, while storing any new data in the cache as just IDs. Once this code has been running for a day, all of the existing data in the cache will have expired and the implementation can be changed to the simpler one.

  1. Pocket dimension, closed timelike curves, above your paygrade, don’t worry about it! 

  2. You might imagine we could get around all this by caching the view, and indeed in this case, it wouldn’t raise the same problems, but in a typically mature Rails application we end up using cached data in other places outside of view generation, so the overall point is worth making. Still, award yourself 1 gold credit. 

Two thoughts about maintainable software

I really enjoyed the most recent episode of Robby Russell’s podcast “Maintainable”, in which Glenn Vanderburg1 talks about capturing explanations about code and systems, along with managing technical debt. It’s a great episode, and I highly recommend pouring it into your ears using whatever software you use to gather pods.

The whole thing is good, but there were two specific points brought up fairly early in their conversation that got me thinking. What a great excuse to write a post here, and make me feel less guilty about potentially never publishing the Squirrel Simulator 2000 post I had promised.

I know; I’m sorry. Anyway, here’s some tangible words instead of that tease. Enjoy!

Documenting the why

At the start of the conversation, Robby asks Glenn what he thinks makes “maintainable” software, and part of Glenn’s response is that there should be comments or documents that explain why the system is designed the way it is.

Sometimes things will be surprisingly complex to a newcomer, and it’s because you tried something simple and you learned that that wasn’t enough. Or sometimes, things will be surprisingly simple, and it’s good to document that “oh, well we thought we needed it to be more complicated, but it works fine for [various] reasons.”

Robby goes on to ask how developers might get better at communicating the “why” – should it be by pointing developers at tickets, or user stories somewhere, or it should be using comments in the code, or maybe some other area where things get documented? And without wanting to directly criticise Glenn’s answer, it brought to mind something that I have come to strongly believe during my career writing software so far: the right place to explain the why is the commit message.

But why not comments?

I’ve lost count of the number of times that I’ve found a comment in code and realised it was wrong. We just aren’t great at remembering to keep them updated, and sometimes it’s not clear when a change in the implementation will reduce the accuracy of the comment.

But it’s already fully explained in the user story/Basecamp thread/Trello card…

I’ve also lost count of the number of times that a commit message contains little more than a link, be it to a defunct Basecamp project, or a since-deleted Trello card, or am irretrievable Lighthouse ticket, or whatever system happened to be in use ten years ago, but is almost certainly archived or gone now, even if the service is still running.

And even if we are lucky and that external service is still running, often these artefacts are discussions where a feature or change or bug is explored and understood and evolved. The initial description of a feature or a bug might not reflect the version we are building right now, so do we really want to ask other developers and our future selves to have to go back to that thread/card/ticket and re-synthesise all those comments and questions, every time they have a question about this code?

Put it in the commit message

Comments rot. External systems, over the timescales of a significant software product, are essentially ephemeral. For software to be truly maintainable, it needs to carry as much of the explanation of the why along with it, and where the code itself cannot communicate that, the only place were an explanation doesn’t rot is where it’s completely bound to the implementation at that momment in time. And that’s exactly what the commit message is.

So whenever I’m writing a commit, I try and capture as much of the “why” as I can. Yes, I write multi-paragraph commit messages. The first commit for a new feature typically includes an explanation of why we’re building it at all, what we hope it will do and so on. Where locally I’ve tried out a few approaches before settling on the one I prefer, I try and capture those other options (and why they weren’t selected) inside the commit message for the approach I did pick.

Conversely, if I am looking at a line of code or a method and I’m not sure about the why of it, I reach for git blame, which immediately shows me the last time it was touched, and (using magit or any good IDE) I can easily step forward and back and understand the origin and evolution of that code – as long as we’ve taken the time to capture the why for each of those changes. And this applies just as much to the code that I wrote as it does to other developers. Future-me often has no idea why I made certain choices – sometimes I can barely remember writing the code at all!

So anyway, in a nutshell, when you’re committing code, try to imagine someone sitting beside you and asking “why?” a few times, and capture what your explanation would be in your commit message.

BONUS TIP: finding that your “why” explanation is a bit too long? That’s probably a signal that you need to make smaller commits, and take smaller steps implementing your feature. I’ve never regretted taking smaller steps, even though I recognise sometimes the desire to “just get it done” can be strong.

Using tests as TODOs

A little later, the conversation turns to the merits of “TODO” comments in the code, and how to handle time-based issues where code needs to exist but perhaps only for a certain amount of time in its current form, before it need to be revisited. It’s not unusual for startups to need to get something into production quickly, even if they know that they are spending technical debt in doing so. Glenn correctly points out that it can be hard to make sure that comments like that get attention in the future when they should.

The problem is that when you put them in there, there’s no good way to make sure you pay attention when the time comes [to address the debt]

I spend a fair bit of my professional time working with a startup that has a very mature (13 years old) Rails codebase, and more often than not, moving quickly involves disabling certain features temporarily, as well as adding new ones. For example, on occasion we might need to disable the regular newsletter mechanism and background workers while the company runs a one-off marketing campaign. To achieve this, we need to disable or modify some parts of the system temporarily, but ensure that we put them back in place once the one-off campaign is completed.

In situations like this, I have found that we can use the tests themselves to remind us to re-enable the regular code. Here’s a very simple test helper method:

def skip_until(date_as_string, justification)
  skip(justification) unless Date.parse(date_as_string).past?
end

Becase we have tests that check the behaviour of our newsletter system under normal conditions, when we disable the implementation temporarily, these tests will naturally fail, but we can use this helper to avoid the false-negative test failures in our continuous-integration builds, without having to delete the tests entirely and then remember to re-add them later:

class NewsletterWorkerTest < ActiveSupport::TestCase
  should "deliver newsletter to users" do
    skip_until('2020-12-01', 'newsletters are disabled while Campaign X runs')
    
    # original test body follows
  end
  
  # other tests 
end

This way, we get a clear signal from the build when we need to re-enable something, without the use of any easy-to-ignore comments at all.

Not all comments?

I’m not completely opposed to all comments, but it’s become very clear to me that they aren’t the best way to explain either what some code does, or why it exists. If we can use code itself to describe why something exists, or is disabled – and then remind us about it, if appropriate – then why not take advantage of that?

And if there’s only one thing you take away from all the above, let it be this: take the time to write good commit messages, as if you are trying to answer the questions you could imagine another developer asking if they were sat beside you. You’ll save time in code reviews, and you’ll save time in the future, since you’ll be able to understand the context of that code, the choices and tradeoffs that were made while writing it – whe why of it – much faster than otherwise.

Here’s a great talk that further illustrates the value of good commit messages, and good commit hygiene in general: A Branch in Time by Tekin Süleyman.

  1. I met Glenn once, at a dinner during the Ruby Fools conference (such a long time ago now). He said some very nice things to me over that dinner, which I’ve never forgotten. So thanks for that, Glenn! 

LGTM

There are a number of techniques that remote teams can use to collaborate, but the main one the client1 relies on is code review via pull requests.

Code review on pull requests can help catch potential issues, but it’s not as good as actual TDD (or any other conscientous testing practice) because once implementation is written, it’s hard to evaluate what aspects of it are intended behaviour and which are side effects, or even bugs.

Code review on pull requests can be good for getting a second opinion on a specific implementation, but they’re not as good as pairing, where ideas and approaches can be discussed and evaluated before any investment is made, and hard-to-spot edge cases can be identified before they are committed into code.

Code review on pull requests is good for communicating between developers about what everyone is working on, but they’re not as good as actual discussion, ideally documented, because without conscious effort to capture context – the why this is being built, and why in this particular way – in either the tests, the commit messages, the pull request description, or ideally all three, it’s often up to the reviewer to try and reverse-engineer the intent and original goals of the piece of work. It’s easy to underestimate how much effort that reverse-engineering can be.

Code review on pull requests is good for avoiding unending, ambigious conversations about what might work to solve a problem, because it’s always easier to measure the value of something concrete than something hypothetical, but by the time the review happens there’s already investment in that particular solution and that particular implementation of that solution. I see the same thing with MVPs, which should be built quickly without particular care, then learned from and finally discarded, but instead are built quickly and without particular care, but then put into production to become the foundation for future work… but I’m digressing; the point is that we developers tend to believe that extant code has more value than it really does, and the momentum of that particular approach can override any fundamental questions2 that a code review might raise.

But… getting good at testing requires effort, and pairing requires a lot more energy than hacking solo, and thoughtfully documenting takes time, and development zen-like detachment from the fruits of our labour doesn’t come naturally either. And all these things require practice, and who has time to practice when there are features to ship!

So we do code reviews on pull requests. LGTM3 :(

  1. At the moment, I spend most of my active development time working remotely for a single client. It’s a Rails project that’s been running for approximately 13 years, with around 5 developers of varying skill levels actively contributing to the backend, where I spend most of my time. 

  2. “Did you consider, maybe, not implementing this at all?” 

  3. “Looks Good To Me”, the hallmark sign that a reviewer has not even checked out and run the code, let along read it carefully and thought about more than syntax. 

I am an omakase chef

I run a restaurant with a single seat, and a single sitting, normally around 10pm.

There is only one item on my menu.

At that time, my sole patron arrives and sits, watching me while I set to work, my hands moving slowly and deliberately with the practice of hundreds of prior repetitions.

The pill is carefully broken in half, and the remainder stashed back in it’s blister.

A small piece of mouldable savoury putty is selected, and carefully shaped around the pill, such that it fully surrounds it, but with the pill off-center, leaving a larger amount of putty at one end.

A Dreamie1 is selected, and is carefully split, and one half is held back in the hand while the other is delicately moulded into the waiting putty, such that the whole can now sit with the Dreamies-half on top, sitting on the putty with the pill hidden directly beneath it. This completes the dish. It is a Dreamie nigiri.

The small morsel is finally placed in front of the diner, who considers it briefly, then eats, and then leaves.

  1. The singular of “Dreamies” is basically unknowable. 

Back on the wagon

Hey, it’s been a while. Sorry about that.

For the past few months I’ve increasingly felt the tug to express thoughts and such, but while most of the world now does that on Twitter, as with Facebook I don’t feel like I can participate on there without condoning some of the awful aspects of social media.

So I’m resurrecting this site, in the hopes that I can write a bit more here to scratch that itch.

Obviously there was no way I could possibly resume writing here without a total overhaul of the design and backend. And then having spent days on it, learning Tachyons in the process, I flicked back to the previous design and, y’know what, it actually wasn’t that bad. But anyway, we’re here now.

Speaking of Tachyons, I did read an interesting article about CSS utility classes and “separation of concerns” that has finally helped me understand the motivations that have driven front-end developers away from “semantic” CSS. As primarily a backend developer, I struggle to shake the dream of writing simple markup for a “thing” and then having different CSS render it appropriately in whatever contexts it might appear, but this helped me understand the journey. I want to re-read that article, because I have a hunch that the destination it describes isn’t actually that far away from the “semantic” one I hope for, just that the CSS might end up being dynamically composed from utility classes by a pre-processor. Maybe.

Some random thoughts I’ve had on return to this site and the codebase behind it:

Anyway, I’m back. Or am I? I think I am. I hope I am.

I’m back.

Getting Started with Spacemacs

I wanted to capture what I like about my editor of choice at the moment. If you’re at all interested in modal editing, or are an experienced Vim user looking for a change, I think there’s a chance you might enjoy Spacemacs. I’ve written this to try and capture what I like about it, and some of the things I wish I’d known when I got started. Hopefully it’s useful to some of you!

Spacemacs

Table of Contents

My history with text editors

Probably every 18 months or so, I seem to get an itch about my current editor, and look around for something different. Often it’s because something is behaving slowly, or I can’t get a feature to work. My editors-of-choice over the last 15 years have been, roughly:

I’m sure all of the issues I experienced were largely my fault, rather than any problem with any of these editors, and I’m totally certain that any frustrations I experienced with any of them could be resolved with enough time and patience. However, when I’m sitting down to work on a project that already requires a lot of though, I don’t want to have to give up a lot of that energy to my editor; I need to be able to get it to do what I would like, with a minimum of energy, headscratching, or waiting for a spinny icon to finish.

Why Spacemacs?

Here’s what I really like about Spacemacs:

Much as I was initially resistant to it, putting all that work into using Vim for half a year did finally sink in, and I can pretty happily jump around within a line, or up and down blocks of code, without having to think too hard about it. I don’t know if I would entirely recant my rant, but the simple fact is that I’ve made the sacrifice and my brain has already been trained, so I might as well accept it. I don’t think I’ll ever be zealatous about the benefits of keeping your hands on the keyboard or anything like that, but I can say that once you do get a handle on movement and text manipulation commands, it doesn’t feel too bad.

… but only if you want it

Sometimes though, as a beginner, it’s just faster to use the mouse, or the arrow keys. And Spacemacs totally supports that. If I’m in a bad mood and don’t want to learn the modal way to do something, I can drag and select text, or jump the cursor around, and it just works. I can click on pretty much anything, from files and directories in the file tree, to links in a markdown document, and they do what you’d expect.

It’s this graceful support for non-modal mechanisms that makes it easy to stick with a modal editor through the rough times and the smooth.

Conventionality and discoverability via which-key

The biggest barrier to me sticking with Vim was feeling like “I know there’s a way to do this better” but having to enter the depths of the Google mines to figure out how. Vim is super-extensible and customisable, but the flip-side of that is that everyone has their own setup and key-bindings and so until you are an expert, you end up with a cobbled together configuration of stuff you’ve found on the internet. As I said above, I’m sure that eventually you would get a handle on this and be able to smooth any rough edges, but I think it’s a significant barrier for people who are already trying to internalise a whole new way of editing.

With Spacemacs, the main way you invoke commands is by hitting the spacebar. Press that nice big giant button and after about half a second, a menu appears with a whole bunch of options about what you might press next, with descriptions of what those are.

The menu, invoked via the spacebar

The commands are organised into sections, all based roughly on mnemonic groupings of what those functions do. So, if you want to do something with a file, chances are that it’s somewhere under the f section. If you want to change the project you’re working on, maybe try p. Want to search for something? Chances are it’ll be under s. Now these mnemonics aren’t perfect (“text” stuff is under x because t was used for “toggles”), but the descriptions are all right there, so the more you look at the menu, the more you internalise which section is which.

Once you get more comfortable, you often don’t need to look at the menu at all, because the combinations become internalised. I don’t need to look at the menu when I want to rename a file, because seeing the menu again and again has helped me learn that it’s SPC f R. Checking the git status of the project is SPC g s. What Spacemacs and which-key do really well is support the learning process, and get you to a point where you can invoke all these commands quickly.

Discovering new functions and key bindings

But it gets even better than that, because you don’t even need to dig around all the the menus until you find the command you were hoping for. If you have an inkling that there should be a more efficient way of, say, making some text uppercase without having to delete and re-type it, you can easily search all of the commands in the editor by hitting SPC SPC and then making a few guesses about what the command name might be. I hit SPC SPC and type “upper”, but none of those look right, so let’s try “upcase”, and bingo, a handful of functions that I might want to use.

Exploring the functions in Spacemacs

I can invoke one by hitting RET, but the menu also tells me what (if any) key conbination would run that function automatically, so if I end up doing this enough times, I’ll probably start trying that combo, and eventually not need to look it up ever again. Every instance of this helps teach me.

Showing the keybindings also shows me where in the menu I would’ve found that key, which over time also gives me clues about where to search for something the next time (“upcase region” is SPC x U, so perhaps there are other text case changing functions under SPC x…).

It also shows me when there are even faster ways of invoking the function using the “evil” bindings, in this case g U. Perhaps I’ll try that out, and if I try it enough times, it gets into my muscle memory, and I get faster.

Layers and conventionality

Learning how the menus are organised also leads to what I mean by “convenionality”. But before I explain this, I need to touch on how Spacemacs is organised. Rather than having you install lots of small Emacs packages (what you might consider plugins), Spacemacs gathers collections of related packages into what it calls “layers”. Every Spacemacs layer comes with a set of key bindings, which the community as a whole has developed together, gathering all of the features and functions of the packages within that layer together. So when you install the “ruby” layer, you get keybindings to run tests, to invoke bundler, to do simple refactorings, to use your preferred version manager, and so on, all ready for you to use and explorable via the menu and function search.

This is not to say that you can’t change things – you totally can! – but you don’t need to. There are similar distributions for other editors that enable similar “sensible” configurations, so this is not to say that Spacemacs is any better than, say, Janus for vim. but for any of these powerful editors, having something that provides this kind of support is really great.

Magit

From what I can tell, a lot of the love for Emacs comes from people talking about how org-mode is amazing and can do anything and it’s the greatest thing in the world, and that it’s worth switching to Emacs just to be able to harness the awesome power of org1. That might be true. I have not used it. I might discover how to use it tomorrow and achieve a similar text-based nirvana.

As a programmer though, there’s a different tool which has me totally sold on Emacs, and that’s Magit, a package for working with the Git version control system.

I used to be a command-line Git jockey. I’d use git add . and git commit -m "Blah blah", and even run interactive rebasing and patch-based adding from the command line. But if you care about creating a great git history, using git from the command line is working against you.

Magit makes it really easy for me to pick files to stage, or even just pick a few lines from those files, and commit just those changes, writing a great commit message while I do, right in my editor.

Using Magit in spacemacs

I really love Magit. With it can I do pretty much anything I knew how to do at the command line, and more, and it encourages me to write the best commit messages I can, and to keep my history tidy too. As far as I’m concerned, Spacemacs is a pretty decent editor with nice ways of teaching and reinforcing how to efficiently edit text, but Magit is a superpower.

So: Getting started

The title of this post is “getting started”, so I’m going to try to share what I did to get going with Spacemacs, in the hope it helps you get started quickly, and see some of the nice features that I’ve been enjoying.

As a caveat, let me say that I use a Mac, and I’m a Ruby developer using Git, so these notes are from that background, rather than a comprehensive set of instructions that will work for everyone.

Installation

Installing Spacemacs is pretty simple. Firstly, you’ll need Emacs. There are a few packages available via Homebrew:

I use emacs-mac because it has patched which enable pixel-level scrolling, and it can also be configured to run without a title bar, which I like because I tend to run Emacs maximised (but not “full screen” since that means something else these days in MacOS).

brew tap railwaycat/emacsmacport && brew install emacs-mac --with-no-title-bars --with-spacemacs-icon

One significant caveat of installing without title bars is that you can’t then drag the window around using your mouse. This can be a real pain, but if you always run Emacs maximised, it doesn’t matter. Unless you know you want this, I’d suggest installing without that option. You can use brew info emacs-mac to see all the installation options if you like.

Ripgrep

While we are at it, also install ripgrep, the super fast search tool that understands version control systems like git:

brew install ripgrep

Spacemacs will then use this tool to do fast searching. Next, install Spacemacs according to their instructions:

Getting Spacemacs

I would encourage you to just follow the instructions on the Spacemacs site, but the gist is this:

git clone https://github.com/syl20bnr/spacemacs ~/.emacs.d

Currently there’s a general recommendation to use the “develop” branch of the Spacemacs repository, since the “master” branch hasn’t seen much attention in a while. I find this a little odd, but that’s how they like to run the project I guess. So:

cd ~/.emacs.d && git checkout develop

Next, start up Emacs! You should see the Spacemacs home screen, and you’ll be prompted to answer a number of questions about how you’d like Spacemacs to be set up. I’d suggest you pick “Evil” as the editing mode, unless you know you don’t want to try to use the Vim-like modal system. Also, pick the “standard” distribution, rather than the minimalist one. Or at least, that’s what I did.

Now Spacemacs will set to downloading a whole bunch of packages and installing them, and this will take a few minutes. This is a perfect time read the Quickstart documentation while you drink your weak lemon drink.

Configuring your installation

Once all the packages have been installed, you’ll be presented with a simple help screen. Read it – it’s going to cover the basics fairly well. If you like, you can dive straight into editing files (take a look at the Cheat Sheet below which might help), but personally, I always like to see what I can tweak when I work with a new editor so once you’re done reading that, hit SPC f e d to open your personal configuration file. This is where all of the installed layers are declared and configured. I’m going to share the settings that I’ve used, but by all means tinker.

Layers

Here’s roughly what my layer configuration looks like:

javascript coffeescript yaml (osx :variables osx-use-option-as-meta nil) helm (auto-completion :variables auto-completion-tab-key-behavior 'complete) better-defaults emacs-lisp neotree git github markdown org (shell :variables shell-default-height 30 shell-default-position 'bottom) (version-control :variables version-control-diff-side 'left version-control-global-margin t) (ruby :variables ruby-version-manager 'chruby ruby-deep-indent-paren nil) (ruby-on-rails :variables feature-use-chruby t) html dash

The lines which aren’t wrapped in parentheses just use whatever defaults exist for the layer. Those that are (e.g. osx or shell) have been configured by me a little. Looking at the layer documentation will explain those settings, but the interesting parts there are that I’ve “unconfigured” the right alt key as the Emacs “meta” key, because I need that key to type # characters.

I’ve also set the Ruby version manager to be “chruby”, but you might need something else. If you want to stick with the defaults, just delete :variables and everything after it, and remove the parentheses.

Other settings

dotspacemacs-maximised-at-startup t

I tend to run Emacs full screen, so I want it to start that way.

dotspacemacs-line-numbers t

Always show line numbers in every file

dotspacemacs-whitespace-cleanup 'changed

For any lines that I have edited, make sure there are no trailing whitespace characters, but otherwise leave other lines untouched. I find this is the best compromise between keeping whitespace in check, but not having commits full of unrelated whitespace changes just because I touched a file that had some.

That’s it for the Spacemacs options, but you can configure other stuff inside the dotspacemacs/user-config function. Here’s a few things that I have:

;; Use two spaces as the tab width (setq-default tab-width 2) ;; Make the modeline look good on Mac OS X (setq powerline-default-separator 'utf-8) ;; Make the right alt key available as meta in case that's useful (setq ns-right-option-modifier 'meta) (setq mac-right-option-modifier 'meta) ;; When saving using cmd-s, exit back into normal mode so that other vim-ish commands just work (global-set-key (kbd "H-s") (lambda nil (interactive) (evil-force-normal-state) (call-interactively (key-binding "^X^S")))) ;; Note that the "^X^S" string above actually needs to be the proper `ctrl-x ctrl-s` characters, which I can't embed in my blog. Best copy them directly from my dotfiles at https://raw.githubusercontent.com/lazyatom/dotfiles/spacemacs-develop/dotfiles/spacemacs ;; Make cmd-t open the project file finder, like other editors (evil-define-key 'normal 'global (kbd "H-t") 'helm-projectile-find-file) ;; Include underscore in word movement commands for Evil mode (dolist (mode-hook '(ruby-mode-hook enh-ruby-mode-hook python-mode-hook js2-mode-hook haml-mode-hook web-mode-hook)) (add-hook mode-hook #'(lambda () (modify-syntax-entry ?_ "w")))) ;; don't align if statements to the if (setq ruby-align-to-stmt-keywords '(if begin case)) ;; set fill-column with for git commits to recommended width (add-hook 'git-commit-mode-hook (lambda () (setq fill-column 70))) ;; Follow symlinks to files without complaining (setq vc-follow-symlinks t)

OK, enough configuration. Let’s actually start editing some stuff!

You’re a vimmer now, ‘arry

First thing’s first, you’re going to need to get used to modal editing. Covering that is way outside of the scope of this article, but here’s some basics.

You’ll start in “normal” mode, which is for moving around, and for manipulating text without actually typing new stuff (so, like, moving lines, copying and pasting and deleting and so on).

If you want to enter some text, you’ll need to enter “insert” mode. There are a few ways to do this, but one is just hitting “i”. Then you can type as much as you like, and hit ESC when you are done to get back to “normal” mode.

To move the cursor around in normal mode, the vimmish way is by using the hjkl keys, which correspond to left, down, up and right. Left and right are pretty obvious, but I used to often get confused which of j and k was up or down. The best way I’ve heard of to remember this is that j looks a little bit like a down arrow, if you can stretch your imagination to that. Bear that in mind and it’ll soon become second nature.

There is a “lot” more to editing using Vim-like commands, and you’ll spend most of your time doing that, so if you’re not very experienced, I would suggest trying out one of the various vim tutorials. There’s even one built in to Spacemacs (SPC h T)!

Editing files and projects

Spacemacs uses a package called projectile to manage projects, but it can be a little unclear how to actually get started with this. Here’s a simple way to get into it.

You can browse the list of projects that Projectile knows about with SPC p p. However, when you get started, this list will almost certainly be empty. Projectile considers a project as any directory that’s under version control. Projects don’t really exist until Projectile discovers them, and the best way of doing that is by opening a file within that directory.

Hit SPC f f to start browsing for a file to open. You can start typing and hit TAB to autocomplete directory and file names, or use ctrl-h to jump up to parent directories to move around quickly. Once you’ve found the file, hit RET to open the file.

Depending on the type of the file, you might be prompted to add a new layer to get all the features for that type of file; it doesn’t really matter what you choose at this point.

Once the file is open, if you hit SPC p p again, assuming you’ve opened a file that was somewhere under version control, you should now see the project in the list, and you can get back to this project easily now.

When you do select a project using SPC p p, you’ll next be prompted to pick a file from that project. For a long time, this confused me, particularly as I moved from one project to the other, and back, in a single editing session. However, this is normal – Spacemacs is just asking which buffer or file from that project that you want to start on.

Cheat Sheet

These are all the commands that I wish I’d known when I got started. It’s also very worth getting a grounding in Vim, including the keys I listed nearer the top of this article; here I’m just including the Spacemacs-specific commands that cover the basics.

Spacemacs includes many other commands, and likely some of them will be better in certain situations than the ones I’ve listed. These are just the basic ones that kept me moving.

These are the basic commands that I use all the time:

There’s a bunch more that I do know and use, and I am certain that I could be using different commands to do a lot of stuff more efficiently, but I think it was really internalising the commands above that got me through the transition from feeling massively slowed down to reasonably efficient at editing and moving text around.

All of these are Vi/Vim commands, but Spacemacs implements them using a package called “evil”, which according to all the reckons on the internet that I’ve read, is hands down the most complete Vim emulation layer available. What this means is that any advice or tricks my Vim-using friends might have, I can also use too, and that’s pretty neat.

General

f d - in rapid succession, will quit out of most menus/commands/minibuffers back into normal mode

ctrl-g - tell Emacs to quit something that’s taking too long

SPC q q - quit Emacs

SPC q R - restart Emacs

q - if you’re in a non-file window, chances are if you hit q, it’ll close that window. Give it a try.

Files, projects and buffers

SPC f f - browse for files and open them

SPC f r - browse for a recently-opened file

SPC f R - rename the current file

SPC f D - delete the current file

SPC p p - show list of projects to choose (you will be prompted to open a file in that project afterwards)

SPC p f - file a file within the current project

SPC p b - show a list of all open buffers for this project (buffers are sort of like “open files”)

SPC b b - show a list of all open buffers

SPC b d - delete a buffer, which basically means “close this file, I don’t want to see it anymore”

SPC TAB - switch back to the previous buffer

SPC f t - toggle open a file tree (use shift-k to go up to parent directories in it)

Windows

SPC w / - split a window vertically

SPC w s - split a window horizontally

SPC 1/2/3...9 - jump to window 1 to 9 (you should see the window numbers in the little mode line)

SPC 0 - jump to the file tree (if it’s open; might actually open it if it isn’t)

SPC w d - close the current window

SPC w m - make the current window the only window

Searching

SPC / - search every file in the project

SPC s s - search (“swoop”) in the current buffer

SPC * - search the current project for the symbol/word under the cursor

* - enter a powerful search “mode” for the symbol/word under the cursor

Editing

SPC i k/j - insert a blank line above or below the cursor without entering insert mode

SPC ; ; - comment out a line of code (although now I know about g c c and all the other Vim-ish g c commands)

Development specific stuff

, t b - run all the tests/specs in this file

, t t - run the test/spec at the cursor

SPC c d - close the test window (“c” is for compilation)

SPC c k - quit the current test run

SPC p a - switch to the alternate file for this one (e.g. from controller to controller test, and back)

Git

SPC g s - open git status. Then hit ? to see the keys that Magit understands. Note that case is important. Hit q to close the Magit buffer.

Spacemacs itself

SPC f e d - open your configuration file

SPC f e R - reload your configuration after editing that file

SPC f e D - compare your configuration to the default one. This is super useful when you’ve updated Spacemacs, since new configuration options become available. When you do this, you enter an “ediff” mode; hit ? to see what keys do, but the basics are: press n and p to move between changes, then a or b to pick which option to use, and q to quit

SPC SPC - search for a function by name, and run it. This is a great way of getting a sense of what Emacs/Spacemacs can do

Documentation and help

Emacs and Spacemacs come with a huge amount of documentation built in, which is extremely useful when you’re trying to figure out how to do something.

SPC h l - search for a layer and then open its documentation, which will show all its configuration options and key bindings

SPC h d f - search for a function and show its documentation

SPC h d v - search for a variable and show its documentation, and current and default values

SPC h d p - search for a package and show information about it

SPC h d k - then enter any combination of keys, and Spacemacs will tell you what function they are bound to and what it will do.

Help, I’m Stuck!

As with any complicated bit of software, it’s possible to get stuck in a menu or lost in some options, and want to back out. Sometimes key bindings you expect to work, will not, because you’ve ended up in one of the “system buffers” that Emacs uses to store command output or something else. Don’t worry – it happens to everyone.

The best way I’ve found to re-orient myself is to hit SPC f r or SPC b r to open the recent file or buffer list, and then get back to a file that I was working on. From there, I can normally get back to moving around my project like I expected. Worst case, just quit (SPC q q) and open Emacs again.

Other Notes

Spacemacs works just as well in the console version of Emacs as the GUI one, so you can happily sync your configuration to remote machines and use everything you’ve learned when editing files on remote servers. And take a look at “Tramp” if you’re interested in another Emacs superpower involving remote files!

Even though I’ve been using Spacemacs for the best part of a year now, I only recently actually read through the documentation (SPC h SPC RET inside Spacemacs, or here). There’s a lot of good stuff in there, particularly about the evil keybindings, and things like managing layouts and workspaces. Once you’ve gotten to grips with some of the basics, I highly recommend just browsing it, and then coming back to it every now and again, to see what jumps out in an “ah! I can use that” kind of way.

I hope this has been useful, either if you’re curious about Spacemacs, or are playing around with it. Thanks for your time!

  1. Perhaps, you might say… joining the borg? Groan

  2. With Spacemacs I actually have it set up so I can hit cmd-s to both save the file and enter normal mode, though I recently also learned about fd and am trying to practice that. 

Here's to the crazy ones (RailsConf 2018)

This is a transcript of a presentation I gave at RailsConf 2018; the actual slides are here; the video is from confreaks.

My name is James Adam, and I’ve been using Ruby, and Rails, for a long time now.

I’d like to share with you some of my personal history with Rails.

Hopefully it won’t be too self-indulgent, and hopefully I won’t bore you before I get to the actually “important” bit at the end. I also want to apologise — every time I come to the US, I seem to get a cold, so please excuse me if I need to cough.

Anyway, let’s get started. Sit back, as comfortably as you can.

You can feel your limbs and eyelids getting heavier. All your worries are drifting away. Let me gently regress you all the way back to 2005.

Welcome to 2005

This is me in 2005. I was just finishing my PhD.

I’d actually discovered Ruby a few years earlier, and I’d totally fallen in love with it. I rewrote most of the code I was using for my research in Ruby. I was so excited about Ruby when I discovered it that I sent this in an email to my friends, who’d all got “proper” jobs writing software, most of them using Java at the time.

The nature of PhDs is that when you finish, you’ve become a deep expert in a topic that’s so narrow that it can be hard to explain how it is connected to anything outside it. So when I finished my PhD in early 2005, I was worried that I was going to be in a similar state professionally — having fallen in love with a language which I’d never be able to use for work, and instead having to return to Java or C++ or something like that to get a job.

I was incredibly lucky. Just as I was finishing my thesis, this excited Danish guy had been starting to talk about a web framework he was writing with the weird name “Ruby on Rails”.

Long story short, a job in London got posted to the ruby mailing list, and so I took the seven hour train journey down from Scotland for an interview, and within a few months I was working, in my first job, being paid to use Ruby, and a very early version of Rails (I think it was 0.9 at the time).

Working on multiple applications

Our team was like a mini agency within a much bigger media company, and the company used a tangled mess of Excel spreadsheets in various departments, in all sorts of weird and wonderful ways. It was our job to build nice, clean web applications to replace them. We were a small team, never more than five developers while I was there, but we’d work on a whole range of applications, all at the same time.

These days, and particularly with Rails 5.2 which was released a few days ago, Rails provides us with pretty much everything you need to write a web application, but’s easy to forget a time when Rails had almost none of the features we take for granted now.

A time before Active Storage, before encrypted secrets, before Action Cable, before Turbolinks, the Asset Pipeline, before resources or REST, before even Rack!

These are the headline features for Rails in Spring 2005, when version 0.13 was released. Migrations were brand new! Can you even imagine Rails without migrations?

In lots of ways, Rails 0.13 is very similar to modern Rails — it has a the same MVC features, models with associations, and controllers with actions, and ERB templates, and action mailer — but in many other ways it was actually closer to Sinatra than what we have in Rails today. To illustrate, the whole framework including dependencies and gems it used was around 45,000 lines of code. By comparison, if you today add Sinatra and ActiveRecord to an empty Gemfile today, and run bundle install, with core dependencies it ends up at around 100k of code.

But the core philosophy of Rails was exactly the same then as it is now — convention over configuration, making the most of Ruby’s expressiveness, and providing most things that most people needed to build a web application, all in one coherent package.

Extracting Engines

So it’s Summer 2005, Rails is at 0.13, and in our team we are building all these applications, and we realise that we’re building the same basic features again and again.

Specifically, things like code to manage authentication — only allowing the application to be used by certain people — and code to manage authorisation — only allowing a subset of those people to access certain features, like admin sections and so on. At the time, I think we had at least four applications under simultaneous development, which is around one app per developer, and it just seemed counter-productive for each of us to have to build the same feature, each in slightly different ways, making it harder for us to move around between the applications, and increasing the chance that we’d each introduced our own bugs and so on. After all, a big part of the Rails philosophy has always been the concept of DRY — don’t repeat yourself.

And these authentication and authorisation features weren’t particularly complicated; they had the same concerns you would expect (login, logout, forgot password, a user model, some mailer templates and so on). So it occurred to us that what we really needed to do was to write this once, and then share it between all the applications we were building, so they could all benefit from new features and bug fixes, and we’d be able to move between the applications more easily.

In modern Rails, we typically share code by creating gems, and those gems integrate with Rails using a mechanism called “Railties”, but that was only introduced at the end of 2009 (on New Years Eve, actually).

Before Railties, we had “plugins”, but they didn’t appear until Rails 0.14.1, so they didn’t exist yet either.

Even using just regular gems was problematic, because this is before bundler, and before we’d figured out how to reliably lock down gem versions for an application. They’d need to be installed system-wide, and so if you had multiple applications running on the same host, upgrading the gems for one application could end up breaking another. Gem freezing also didn’t appear in Rails until version 0.14.

So without any existing mechanisms, we had to roll up our sleeves and invent something ourselves.

So in the late summer of 2005, we extracted all of the login and authorisation code, including controllers and models and views and so on, into a separate repository and then wrote a little one-file patch library, which was loaded when Rails started. This library added paths to the controllers and models into the load paths for Rails, and made a few monkey-patches to Rails’ internals to get everything else working nicely.

Originally this one-file patch was called “frameworks”, but fairly soon after it got renamed to “engines”. The name “engines” was actually the idea of Sean O’Halpin, who was my boss at the time and has been programming with Ruby for even longer than me.

The dawn of plugins

In October of 2005, a few months later, Jamis Buck added an experimental “plugins” feature to Rails.

A “plugin” was just a folder of code that contained a “lib” directory and a file called “init.rb”, and the “plugins mechanism” would just iterate through subdirectories of “vendor/plugins”, trying to load files called init.rb if it could find them. Very simple.

We spotted this feature being added Rails and so I emailed Jamis and David to say “hey, we’ve been working on something similar — if you were interested, we’d be happy to contribute!”

We got a very nice reply, the gist of which was “that sounds very interesting, but perhaps you can package that up as a plugin itself and we’ll see how people use it”. So that’s exactly what we did, resulting in the “Engines Plugin”, which let you treat other plugins as these vertical MVC slices which could be shared between applications. This is the first homepage for it, hosted on RubyForge.

I also released the first engine, the “Login Engine”, which wrapped up code from one of the original authentication generators we’d used, along with a few tweaks that we found useful.

That was November 1st, 2005.

The engines plugin is released; the controversy begins

People got pretty excited. Like, super-excited. Which was really exciting for me too.

There was enthusiasm for the demonstration engine that I released, and it seemed that people understood the idea behind what we were doing. Someone tried to turn Typo, which was the first really popular Rails-based blogging platform, into an engine, so they could add blogs into their application.

A lot of people got pretty enthusiastic specifically about not having to write the same old login stuff again and again. Some people, I think, hoped that they would never have to write another login system again ever, and that the simple one we released with work seamlessly for everyone.

But then somebody got so excited, that they started talking about “engines within engines, depending on other engines” and I think it was this idea that ultimately pushed DHH over the edge, and about 10 days later he wrote the first post about engines on the official Rails blog.

In the post, David talked about his distrust of the dream of component-based development, and that it’s better to build your own business logic than try to adapt something that someone else wrote, and that we shouldn’t expect to be able to plug in or swap out these high-level components like forums and galleries and whatever, and never have to build them ourselves.

And I agreed with him, but tried to clarified that what engines were great for was extracting code that you’ve written, and sharing it around a bunch of apps that you’re working on at the same time, as long as those features were relatively isolated from the rest of the application. And I think David agreed with that too.

I could see his perspective: when you just have a single application to work on, like, say … Basecamp, then chances are that you can and should develop as much of the business logic yourself as you can. But if you’re working on 3 or 5 or 10 applications, at the same time, then chances are that the balance of value vs cost of sharing starts to tip the other way.

I was pretty happy with that conversation — it seemed like we generally understood and agreed about the potential benefits and dangers of what I was proposing. I’d shared an idea, and David had merely expressed a bit of caution, but a bunch of people had become super excited by it, maybe a little too excited, and on the other side a LOT of other people took David’s post as a declaration that the idea was fundamentally bad and to be avoided at all costs.

And so that’s basically how things played out for the next three years. Every now and then someone would write a blog post saying “Rails needs something like engines” or “engines are actually pretty useful” and they’d be met with the reaction “Didn’t you know that engines are ‘too much software’ (whatever that means), and like, really bad?”

And so I’d write a comment or another blog post trying to be reasonable and say “well, it’s more complicated than that” and occasionally the author might add a little clarification to their post but by that point it’s too late and you’ve got people commenting that rails engines are actual evil.

I call this time the wilderness years.

The Wilderness Years

During this time I tried to respond to the criticisms of the engines concept, with varying degrees of success. It was occasionally… quite frustrating.

I spoke at a bunch of conferences about plugins, and sometimes engines, and also tried to gently steer the development of the plugin architecture in Rails to reduce the amount of patching that the engines plugin needed to do, by adding things like controlling plugin loading order, exposing Rails configuration and initialisation hooks to plugins, and stuff like that.

Plugins became very popular, and went from being shared as links on a wiki page to having their own directory you could search and comment on.

Here’s an example of a fun plugin that I wrote for one of those presentations. See, I’m having fun!

And when, if I did mention engines in those presentations, I tried to explain that there were valid use cases, and sure, you could use them in a terrible way, but that doesn’t mean people should never use them. I hoped that those presentations, if not actually changing anyone’s mind, might’ve at least softened people a little to the idea that engines might not be 100% terrible.

But then on the official plugin directory you’d get someone tagging the engines plugin as “shit”, and the cycle would start again. (I never did find out who that was.)

Some people would go to lengths to explain why “Rails Engines” were bad, but I’d try to write a short comment to respond to each of their points and hopefully clear up any misconceptions about what the engines plugin did and what engines were good for.

In this particular case, though, what was super confusing is that the same people then released their own plugins trying to basically do the same thing!

The wilderness period lasted so long that some companies even wrote engines-like plugins without realising that engines even existed! (Brian and I actually had a conversation afterwards, and talked about merging the projects).

Rails 3: an evolution

So this is all happening between 2006 and 2008, during which a new Ruby web framework appeared, called Merb.

It was designed to be extremely fast — largely because it didn’t do very much — and be particularly good at handling many simultaneous requests and things like file uploads. Unlike Rails, which was at the time a relatively tightly-coupled set of frameworks, Merb was designed to be extremely modular, so it could (for example) support multiple ORM frameworks. It was also designed to have clear and stable internal APIs, since much of the merb framework was written as optional plugins.

One of the developers most involved in Merb was Yehuda Katz, who eagle-eyed people will have spotted was generally sympathetic to the concept of “engines”, and so it’s probably not surprising that in 2008, Merb introduced their implementation of the idea, called “Merb slices”, to a generally positive response from the Ruby community.

But it’s not a huge surprise that this is how the most popular Rails podcast at the time chose to frame that.

And I don’t blame the presenters for thinking or saying that, it was just a representation of the opinion in the community as a whole, at that a time.

This is a painting of “Sysiphus”, who in Greek mythology was cursed by the Gods by being forced to roll an immense boulder up a hill only for it to roll down when it nears the top, repeating this action for eternity. These days it’s a common image invoked to describe tasks that are both laborious and futile.

A surprising development

So we come to the end of 2008. Rails is about to reach version 2.3. The controversy had largely died down — people who got some value out of working with engines were pretty happy, I hope! and the people who thought they were evil seemed to have forgotten about they existed.

So you can imagine my surprise when I received this email from DHH with the subject line, “I repent”.

I think I actually became giddy at the time. Rails core had decided that engines weren’t evil, and that they were going to be integrated into the framework. My work… was done.

OK, not really. Without going into a huge amount of detail, in Rails 2.3, plugins absorbed some of the core engines behaviour. They could provide controllers, views and most other types of code. This was released in Rails 2.3, in March 2009.

At the same time, Merb and Rails decided to merge, and Rails 3 would be the end result. The goal of doing this was, in part, to establish some clear, stable APIs within Rails, that other libraries and plugins could rely on, so they they didn’t break when Rails was upgraded. This was a fairly significant rewrite of a lot of the core parts of Rails in order to create those APIs.

Yehuda and Carl Lerche did much the work, and as part of it, they decided that rather than having a Rails application, and these “engine” things inside it that looked like a Rails Application and got access to the same hooks and config and so on, that instead, the outer application itself should just be a Rails Engine with a few other bells and whistles. So I guess the “engines inside of engines” person actually got their wish!

This was released as Rails 3.0, in 2010.

Finally, with Rails 3.1, released in August 2011, the last two bits of work that the engines plugin did — managing migrations from engines, and assets became part of Rails, and the plugin that I had written was officially deprecated.

The Hype/Hate Cycle

You have probably heard of the Gartner Hype Cycle, which is a way of understanding how technology trends evolve.

We have the initial creation or discovery of the technology, then the peak of inflated expectations, where everyone is excited about having jetpacks or living on the moon, but then the trough of disillusionment, when it turns out it’s actually much harder to build a jetpack than we thought, and there are a lot of things we need to built one that aren’t ready yet. But eventually technology starts to climb the slope of enlightenment, as we figure all those little things out and iron out the problems so we don’t set our legs on fire and so on, and we finally get to the plateau of productivity, when zipping around on our jetpacks seems pretty ordinary and we look back at old movies of people moving around using their legs and laugh about how quaint they seem.

And I think we can use a similar cycle to understand how the Rails community reacted to the “engines” concept too. For engines, it took just under six years from idea to acceptance.

We have the same starting point, and the same peak of inflated expectations (“I’ll never need to write login code again!!”), but then we enter what I like to call the TROUGH OF RECEIVED OPINIONS, where some big names in the community have been like “woah woah woah”, and we’ve personally haven’t actually tried using the technology but we’ve heard it sucks and so basically it’s the worst thing ever. And then for about three years, we scrabble up the SLOPE OF FEAR, UNCERTAINTY and DOUBT, where people find themselves thinking “hey, wouldn’t it be great if I could share this slice of functionality between all my apps?”, but when they try, they get bogged down in all the blog posts, often from years ago saying “no! It sucks!” and so they give up. And then, finally we reach the plateau of “oh — are those still a thing?”

And as you can see, at the end of the cycle, we are just about neutral. We’re basically back where we started, but at the very least I can finally put the boulder down and stop pushing it up the hill :-)

If you’d like a nice summary, I found this quote in the book “Rails 3 in Action”, which was published around the same time.

Engines: there when you need them

So, what changed in 2008? Well, I think think it’s quite simple in retrospect. Rails was originally extracted from Basecamp, the software that DHH built and still works on today. At the start of Rails life, Basecamp was the only Rails application that David worked on, but between 2005 and 2008, 37signals added another three flagship applications, along with a few other smaller ones like Writeboard and Ta-da list.

Their small team — I think it was four developers at that point — had to build and support all those applications… at the same time… that… sounds… familiar, doesn’t it? :)

In the “Rails Doctrine”, which is a somewhat-intentionally-provocative essay that David wrote about two years ago, there’s a section called “Provide sharp knives”.

What it basically says is that with some of the tools that Rails gives you, it’s definitely possible to get in a mess. But instead of protecting you from misusing them by keeping them from you altogether, we should trust ourselves to use those tools and approaches sensibly. Concerns is one example of a “sharp knife” — some people think they encourage sweeping complexity under the rug, while others think that used appropriately, it’s not a problem and the benefits outweigh the risks.

And that’s exactly what the engines concept is: a sharp knife. For around 6 years, it was a little too sharp to be included in Rails’ silverware drawer, but it seems like perhaps now we can be trusted with it. And these days, lots of popular libraries are engines.

Devise, which is an extremely popular authentication library, is an engine. The Spree e-commerce platform is an engine, and you can get content management systems like Refinery CMS, which is an engine too. Even the new Active Storage feature in Rails, is implemented as an engine inside.

Welcome back to 2018

OK, that’s the end of our trip back to 2005, and we’re now back in the present. This is a good moment to take a stretch.

But before we start the third act, I wanted to mention one little thing that has nothing to do with Rails, or engines. Most of what I’ve talked about happened at least ten years ago, and when I was writing this talk, I wanted to make sure that I hadn’t inadvertently distorted how things played out in my memory.

All of the comments and posts I’ve used are real, but when I tried to find all these original newsgroup posts and articles and blogs so on that were written at the time, what I found was that almost all of sites I have referenced are either totally gone, or only partially available (e.g. all the discussion comments on the rubyonrails blog have disappeared, loud thinking is gone, even Ruby Forge is gone…)

I think that history is interesting and important, and it’s kind of mind-boggling that without archive.org, information that’s only ten years old might otherwise be basically gone forever. So if you can, please support archive.org. They accept donations at their website, and I genuinely believe they are providing one of the most valuable services on the web today.

The History of Rails

OK, back to Rails. So at the start of this talk, I did say that I didn’t want this to be too self-indulgent, or to paint myself as some misunderstood genius or hero, finally proven right.

I am sure there are many other stories like this, in many other Open Source projects. But what I think is interesting about this journey is that it shows that the history of Rails can be viewed as a history of opinions.

Rails is “opinionated software”, which is great because it saves us a lot of time by allowing us to offload lots of decisions about building software, in exchange for accepting some implicit constraints. Following those constraints is what we sometimes call the “Rails Way”.

Some of those opinions are about how we use Ruby as a programming language — about how you should be able to express behaviour at the level of a line of code. An example of this are the methods that Rails adds to objects like String and Array.

Objects in a Rails application tend to have a lot of methods. Some people believe that it’s better to try to minimise the number of methods on an object, but it’s Rails’ opinion that the tradeoff is worth it, in order to be more expressive. Neither is wrong or evil. They are just two different opinions.

Other opinions are at a more architectural level, and are ultimately about how we ought to structure the applications we build when using Rails.

If you build your URLs and controllers in terms of REST and resources, you’ll be able to use a lot more of the abstractions and high-level mechanisms that Rails provides. But if you like to add lots of custom actions into your controllers, Rails can’t stop you, and it won’t stop you, but you’ll have to do a lot more work yourself to wire things up.

But that’s not the same as saying “if you don’t use resources, your code is bad” — it’s just the guiding opinion that Rails has.

What might not be obvious, though, is that over the 14 years of Rails’ life so far, those opinions haven’t always existed, and haven’t always stayed the same.

The REST verbs and resource-based architecture weren’t a part of Rails for almost two years. Inline Javascript was fine until 2011 when Rails switched to unobtrusive javascript. If you wanted to send an email when a user signed up, before Rails 4.0 you might’ve written an observer to reduce the coupling between creating a user record and dealing with emails, but they were removed, and in the modern Rails Way, you’d probably create a concern which mixed in callbacks to your User model.

I think a particularly interesting is example is Active Resource.

It used to be a part of the Rails framework, an evolution of the “actionwebservice” framework, which used to support SOAP, Dynamic WSDL generation, XML-RPC, and all the acronyms that David mentioned as “WS-deathstar” in his keynote yesterday.

ActiveResource let you save and load remote data using JSON over HTTP, using the same ruby methods as you’d use on a regular Active Record model. It made it easy build things like micro services and so, I think, acted as a signal that you could and should do that. It was removed in Rails 4.0, which might be one of the first indications of the current opinion that a Majestic Monolith is a more productive way to work overall.

The only constant is change

The purpose of highlighting these changes of opinion is not to say that DHH, or anyone who is or was in Rails Core is frequently wrong; it’s to show that even in the world of opinionated software, opinions can change.

Fundamentally, what is and isn’t in Rails is driven by the needs of the people who write it, and to a greater or lesser extent, that means people building applications like Basecamp. But not everybody is building an application like that. I think more and more of us are working on Rails applications that have been around for a long time, in some cases ten years or more, and those kinds of applications have different needs and experience different pressures than one where the developer controls all the requirements and is free to rewrite it if they choose to, at almost any time.

According to builtwith.com there are almost 1.1 million sites running on Rails at the moment, so it’s statistically extremely unlikely that Basecamp, as a piece of software or as a company, sits at the exact centre of all the different needs and pressures and tradeoffs those other applications and companies have.

We are the stewards of the future of Rails

Right now there are differing opinions in the community about what the future of Rails might include.

The majestic monolith vs. micro services; concerns and callbacks vs smaller object composition; system tests vs. unit testing & stubs… these tensions are good. We need people to be pushing at the boundaries of the Rails Way, to figure out what’s next.

If we just sit back and wait for a relatively small group of people to tell us what the future of Rails looks like, then it will only be a future that suits their particular, unavoidably-limited contexts.

In 2014, 37signals changed their name to Basecamp and returned to maintaining a single application, so some of the motivation from within Rails Core for things like engines is naturally going to diminish. And that’s understandable: it’s an itch they may no longer have. But I wonder how many other software itches there are, which Basecamp doesn’t experience, but hundreds or thousands of other applications and developers do.

We need more voices sharing their experiences, good and bad, with the current Rails Way and we need people to build things like Trailblazer, ROM, and Hanami, and dry-rb, and then others to try using them and learning from them.

Probably none of these projects will ever usurp Rails, but they might contain ideas about how to build software, or how to structure web frameworks, which are new and useful. And like Merb, they might end up influencing the direction Rails takes towards something better for many of us. They might already have found some conceptual compression, to use the phrase from David’s Keynote, that we can adopt or adapt.

And there’s no reason why the people doing that exploration can’t be you, because who else is going to do it? You are the Rails community. You work with Rails all the time. Who better than you to spot situations where a new technique or approach might help. Who better than you to try and distill that experience into beautiful, expressive code that captures a common need.

You can be one of the crazy ones. The misfits. The rebels. The troublemakers. The round pegs in square holes. The ones who see things differently.

As it says at the bottom of the “Rails Doctrine”:

“We need disagreement. We need dialects. We need diversity of thought and people. It’s in this melting pot of ideas we’ll get the best commons for all to share. Lots of people chipping in their two cents, in code or considered argument.”

Life in the Big Tent

OK, wonderful. Rails now embraces all manner of opinions under its big tent. But what happens when you have your idea, but people don’t quite understand it immediately, and things get a little out of control and suddenly people are decrying it as evil?

I feel for you, genuinely, because when I released engines, the main way people expressed these kinds of opinions was in the comment form of a blog. But we are now living in the age of the tweet, where many people don’t think twice about unleashing a salvo of 280 character hot takes out into the world. I’m not sure that we live in an age of “considered opinion” at the moment.

So what can we do? Well, two things.

Be considerate

Firstly, as consumers of open source technology, I think we could all try our best to avoid sharing opinions like that. If you’ve had a bad experience with a technology or a technique, then that’s totally valid and you can and absolutely should share that experience. But don’t do it in a tweet, or if you MUST do it in a tweet, try to at least be balanced.

Even better, start a blog, or post on Medium, and write as much as you can about your experience and your context, and share a link to THAT on twitter.

Be patient

Secondly, if you are lucky and generous enough to actually try to contribute a new idea to this, or any other community, try not to become demotivated if people don’t understand the point at first. This is that first blog post about Rails on the 37signals blog, in early 2004. Look at the first comment.

What this shows is that the value of why you’re doing something differently, is often not immediately obvious to people. You will have to patiently explain it. Sometimes again and again, maybe for years and years. And you won’t be able to convince everyone, but you might reach someone who finds it interesting or useful, who might then reach someone else, and before you know it, lots of people are getting value from your little idea, and it could end up making a big difference after all.

The subjective value of ideas, and how to stay sane

There’s one last thing I’d like to say. When you make something, and it receives criticism, especially on the internet, from strangers, it can be very hard to deal with, sometimes so much so that we might stop creating things altogether, or never even try.

When I was a researching this talk, I stumbled across an old blog post, from 2006 — actually by DHH, would you believe it — that captured a good way of dealing with situations like this. I’m going to paraphrase it.

View your idea, or the thing you’ve made, as a pearl, not a diamond. When someone responds to your idea and points out all the flaws, the situations where it might not work for them, that’s OK, because what they’re asking for is a diamond. They want you to give them something they consider flawless. They want something perfect. But you need to try to remember that however that want is expressed, constructively or vitriolically, or wherever in between, that it’s not your job to make a diamond for them.

Instead, all you can offer them is the pearl you’ve made, and if that’s not good enough, then:

Thank you.