Rails 5.1 doesn't share thread_mattr_accessor variable

Mohit Natoo

By Mohit Natoo

on 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.

1
2class Player
3  thread_mattr_accessor :alias
4end
5
6class PowerPlayer < Player
7end
8
9Player.alias = 'Gunner'
10PowerPlayer.alias = 'Bomber'
11
12> PowerPlayer.alias
13#=> "Bomber"
14
15> Player.alias
16#=> "Bomber"
17

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.

1
2class Player
3  thread_mattr_accessor :alias
4end
5
6class PowerPlayer < Player
7end
8
9Player.alias = 'Gunner'
10PowerPlayer.alias = 'Bomber'
11
12> PowerPlayer.alias
13#=> "Bomber"
14
15> Player.alias
16#=> "Gunner"
17

Stay up to date with our blogs. Sign up for our newsletter.

We write about Ruby on Rails, ReactJS, React Native, remote work,open source, engineering & design.