Advanced Rails - Building Industrial-Strength Web Apps in Record Time

(Tuis.) #1

Blank


62 | Chapter 2: ActiveSupport and RailTies


Blank core_ext/blank.rb


ActiveSupport adds theblank?instance method to all objects. This method returnstruefor
the empty string, a string consisting only of whitespace,false,nil,[],or{}. This provides
an easy shortcut to test for missing values—for example, a string can be tested withs.blank?
rather than(s.nil? || s.empty?).


Class Attribute Accessors core_ext/class/attribute_accessors.rb


ActiveSupport extends theClassclass to provide friendly attribute accessors specific to a
Classobject. These attribute accessors (cattr_reader,cattr_writer, andcattr_accessor)
mirror theattr_reader,attr_writer, andattr_accessormethods onModule. They define
accessors at both the class and instance level.
class C
cattr_accessor :log
self.log = ""


def initialize
log << "#{self.inspect} created\n"
end
end

3.times {C.new}

puts C.log
# >> #<C:0x10a7d6c> created
# >> #<C:0x10a78d0> created
# >> #<C:0x10a7894> created

These methods use class variables instead of instance variables:


C.log == (class C; @@log; end) # => true

There are also module-level attribute accessors:mattr_reader,mattrwriter, andmattr
accessor.


Class Inheritable Attributes core_ext/class/inheritable_attributes.rb


Inheritable attributes are attributes defined on a class object (as with class attribute acces-
sors). However, the attributes and their values are cloned to children when the class is
subclassed. There are three flavors of inheritable attributes: normal, array, and hash. As
with class attribute accessors, accessor methods are defined at both the class and instance
level, so they can be accessed from instances of the class.


Class inheritable attributes support the inheritance structure used by ActiveRecord. Attributes
such as connection specifications can be defined inActiveRecord::Base, and they will be
passed on to subclasses, while they can still be overridden in the subclasses if needed.

Free download pdf