Skip to content
This repository
Browse code

AS guide: documents internal attributes

  • Loading branch information...
commit 466948e64b2b7a86297b02b00289d69413e781f1 1 parent 18f6d53
Xavier Noria authored February 06, 2010
38  railties/guides/source/active_support_core_extensions.textile
Source Rendered
@@ -553,6 +553,44 @@ attr_accessor_with_default :primary_key, 'id'
553 553
 
554 554
 NOTE: Defined in +active_support/core_ext/module/attr_accessor_with_default.rb+.
555 555
 
  556
+h5. Internal Attributes
  557
+
  558
+When you are defining an attribute in a class that is meant to be subclassed name collisions are a risk. That's remarkably important for libraries.
  559
+
  560
+Active Support defines the macros +attr_internal_reader+, +attr_internal_writer+, and +attr_internal_accessor+. They behave like their Ruby builtin +attr_*+ counterparts, except they name the unerlying instace variable in a way that makes collisions less likely.
  561
+
  562
+The macro +attr_internal+ is a synonim for +attr_internal_accessor+:
  563
+
  564
+<ruby>
  565
+# library
  566
+class ThirdPartyLibrary::Crawler
  567
+  attr_internal :log_level
  568
+end
  569
+
  570
+# client code
  571
+class MyCrawler < ThirdPartyLibrary::Crawler
  572
+  attr_accessor :log_level
  573
+end
  574
+</ruby>
  575
+
  576
+In the previous example it could be the case that +:log_level+ does not belong to the public interface of the library and it is only used for development. The client code, unaware of the potential conflict, subclasses and defines its own +:log_level+. Thanks to +attr_internal+ there's no collision.
  577
+
  578
+By default the internal instance variable is named with a leading underscore, +@_log_level+ in the example above. That's configurable via +Module.attr_internal_naming_format+ though, you can pass any +sprintf+-like format string with a leading +@+ and a +%s+ somewhere, which is where the name will be placed. The default is +"@_%s"+.
  579
+
  580
+Rails uses internal attributes in a few spots, for examples for views:
  581
+
  582
+<ruby>
  583
+module ActionView
  584
+  class Base
  585
+    attr_internal :captures
  586
+    attr_internal :request, :layout
  587
+    attr_internal :controller, :template
  588
+  end
  589
+end
  590
+</ruby>
  591
+
  592
+NOTE: Defined in +active_support/core_ext/module/attr_internal.rb+.
  593
+
556 594
 h4. Delegation
557 595
 
558 596
 The class method +delegate+

0 notes on commit 466948e

Please sign in to comment.
Something went wrong with that request. Please try again.