Skip to content

Commit 95c2963

Browse files
flavio-bzzak
andcommitted
Clarification about instance-level methods defined by cattr_accessor
Rewrote the segment to make it explicit that class variables are in use, and the implication of changing their value. The example was updated to make this clear. Co-authored-by: zzak <[email protected]>
1 parent 46d2afa commit 95c2963

File tree

1 file changed

+13
-9
lines changed

1 file changed

+13
-9
lines changed

guides/source/active_support_core_extensions.md

Lines changed: 13 additions & 9 deletions
Original file line numberDiff line numberDiff line change
@@ -977,19 +977,23 @@ class MysqlAdapter < AbstractAdapter
977977
end
978978
```
979979

980-
Instance methods are created as well for convenience, they are just proxies to the class attribute. So, instances can change the class attribute, but cannot override it as it happens with `class_attribute` (see above). For example given
980+
Instance methods are also created for convenience, but they are simply proxies to the internal value which is shared among the class. As a result, when an instance modifies the value, this affects the entire class hierarchy. This behavior is different than `class_attribute` (see above).
981+
982+
For example:
981983

982984
```ruby
983-
module ActionView
984-
class Base
985-
cattr_accessor :field_error_proc, default: Proc.new {
986-
# ...
987-
}
988-
end
985+
class Foo
986+
cattr_accessor :bar
989987
end
990-
```
991988

992-
we can access `field_error_proc` in views.
989+
instance = Foo.new
990+
991+
Foo.bar = 1
992+
instance.bar # => 1
993+
994+
instance.bar = 2
995+
Foo.bar # => 2
996+
```
993997

994998
The generation of the reader instance method can be prevented by setting `:instance_reader` to `false` and the generation of the writer instance method can be prevented by setting `:instance_writer` to `false`. Generation of both methods can be prevented by setting `:instance_accessor` to `false`. In all cases, the value must be exactly `false` and not any false value.
995999

0 commit comments

Comments
 (0)