Superclass mismatch when inheriting from Struct.new
We recently ran into an error that took a little thought:
TypeError: superclass mismatch for class FooJob
Specifically, FooJob
was a DelayedJob custom job class. Unfortunately, DelayedJob had recommended a structure like this:
class FooJob < Struct.new(:bar, :baz)
def perform
# ...
end
end
When this class was required more than once, it gave us our TypeError
. (I think it was loaded from two different paths.) Although the two structs made by Struct.new
were created with the same arguments, they’re actually different objects, hence the superclass mismatch.
Moral of the story: you should never inherit from Struct
! Do this instead:
FooJob = Struct.new(:bar, :baz) do
def perform
# ...
end
end
After that change, our TypeError
went away. Good to know!
Update: I submitted a pull request to hopefully prevent other people from falling into this same trap.
Reactions
@benjaminoakes Ha, I almost sent that exact same PR ~6 mos. ago. #theniforgot
— Jordan ⋈ Running (@swirlee) October 15, 2013
@benjaminoakes Interesting, I've used inheritance before. Good to know - thanks for posting!
— Jason Wieringa (@jwieringa) October 15, 2013