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

(Tuis.) #1

Deprecation


58 | Chapter 2: ActiveSupport and RailTies


3.const_missing callsDependencies.load_missing_constant(Object, :Store).
4.load_missing_constantattempts to find and loadstore.rbsomewhere in its list of load
paths (Dependencies.load_paths). It fails to find such a file.
5.load_missing_constantsees thatapp/models/storeexists and is a directory. It creates a
module, assigns it to the appropriate constant, and returns.

Deprecation deprecation.rb


TheActiveSupport::Deprecationmodule provides a method by which old APIs are marked
for removal. At its core, it is just a fancy warning mechanism. When old APIs are used, they
generate a warning in development or test mode. Deprecation warnings are invoked
through the ActiveSupport::Deprecation.warn(message, callstack) method. The
ActiveSupport::Deprecation.silencemethod silences those warnings for the duration of
the provided block.


Thedeprecateclass method provides an easy way to mark a method as deprecated while
still making it available. It decorates the given method with the deprecation warning.
def find_first(conditions = nil, orderings = nil, joins = nil) # :nodoc:
find(:first, :conditions => conditions, :order => orderings, :joins => joins)
end
deprecate :find_first => "use find(:first, ...)"


ActiveSupport::Deprecation.behavioris aProcthat is called when a deprecation warning is
triggered. It takes two arguments: the deprecation message and the callstack. It can be
replaced to modify the default behavior. By default, in the test environment, deprecation
warnings print to the standard error stream. In development, they go to the logger. In
production, deprecation warnings are silenced.


Deprecated instance variables


ActionController defines a set of objects that are made available to controllers. These
objects used to be publicly available instance variables; this usage is now deprecated. For
example, the session object (available to controllers through thesessionandsession=
methods) used to be accessible as@session. This creates a problem: how do we intercept
access to these deprecated instance variables? Ruby isn’t so helpful as to provide us a hook
that informs us upon instance variable access.


Rails uses a neat trick: a proxy class. The protected objects were moved out of those
instance variables and moved into “internal” instance variables (which begin with an
underscore). The old instance variables were replaced with instances ofActiveSupport::
Deprecation::DeprecatedInstanceVariableProxy, which proxies to the real objects. When a
method is called on these proxies (such [email protected]), a warning is generated before dele-
gating the call to the real object. This is a common Ruby trick that is used in several other
places in Rails—replacing a standard object with a proxy object that responds in a special
way to certain methods.

Free download pdf