Rails 5.1 doesn't share thread_mattr_accessor variable

Mohit Natoo

Mohit Natoo

May 16, 2017

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"

If this blog was helpful, check out our full blog archive.

Stay up to date with our blogs.

Subscribe to receive email notifications for new blog posts.