This blog is part of our Rails 5.1 series.

Rails 5.0 provides mattr_accessor to define class level variables on a per thread basis.

However, the variable was getting shared with child classes as well. That meant when a child class changed value of the variable, then its effect was seen in the parent class.

class Player
  thread_mattr_accessor :alias
end

class PowerPlayer < Player
end

Player.alias = 'Gunner'
PowerPlayer.alias = 'Bomber'

> PowerPlayer.alias
#=> "Bomber"

> Player.alias
#=> "Bomber"

This isn’t the intended behavior as per OOPS norms.

In Rails 5.1 this problem was resolved. Now a change in value of thread_mattr_accessor in child class will not affect value in its parent class.

class Player
  thread_mattr_accessor :alias
end

class PowerPlayer < Player
end

Player.alias = 'Gunner'
PowerPlayer.alias = 'Bomber'

> PowerPlayer.alias
#=> "Bomber"

> Player.alias
#=> "Gunner"