Prev | Current Page 49 | Next

Brad Ediger

"Advanced Rails"

Instead, JRuby must keep track of objects manually, which adds a great
amount of overhead. As the same tricks can be achieved with methods like
Module.extended and Class.inherited, there are not many cases where ObjectSpace
is genuinely necessary.
Delegation with Proxy Classes
Delegation is a form of composition. It is similar to inheritance, except with more conceptual
???space??? between the objects being composed. Delegation implies a ???has-a???
rather than an ???is-a??? relationship. When one object delegates to another, there are
two objects in existence, rather than the one object that would result from an inheritance
hierarchy.
Delegation is used in ActiveRecord??™s associations. The AssociationProxy class delegates
most methods (including class) to its target. In this way, associations can be
lazily loaded (not loaded until their data is needed) with a completely transparent
interface.
DelegateClass and Forwardable
Ruby??™s standard library includes facilities for delegation. The simplest is
DelegateClass. By inheriting from DelegateClass(klass) and calling super(instance)
in the constructor, a class delegates any unknown method calls to the provided
instance of the class klass. As an example, consider a Settings class that delegates to
a hash:
require 'delegate'
class Settings < DelegateClass(Hash)
def initialize(options = {})
super({:initialized_at => Time.


Pages:
37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61