“...I've been working since 2008 with Ruby / Ruby on Rails, love a bit of Elixir / Phoenix and learning Rust. I also poke through other people's code and make PRs for OpenSource Ruby projects that sometimes make it. Currently working for InPay...”

Rob Lacey
Senior Software Engineer, UK

Don't subclass Struct.new

Ran into a really irritating issue this week. While trying to test a new install of Resque . Attempting to run a worker kept return a ‘subclass mismatch error’ on some classes in our Rails application. Our Blah::User class was seemingly being reloaded and on the second reload the anonymous parent class had a mismatch. Make sense.

module Blah
  class User < Struct.new(:id, :email)
    def to_s
      "#{id} #{email}"
    end
  end
end

According to this Reddit post you shouldn’t subclass structs. Taking another look at this the above seems incorrect, I never noticed it before but the above would create a new anonymous Struct class and would immediately subclass it. The anonymous class on it’s own is not required, and it appears is the cause of this class loading oddness. The problem is resolved when we define the Struct without subclassing and we haven’t got any anonymous Struct classes using up memory.

module Blah
  User = Struct.new(:id, :email) do
    def to_s
      "#{id} #{email}"
    end
  end
end
GPK of the Day Bad Breath SETH