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

(Tuis.) #1

Module


70 | Chapter 2: ActiveSupport and RailTies


Module


Aliasing core_ext/module/aliasing.rb



  • alias_method_chain(target,feature)wraps a method in a new function, usually to
    add a new feature. This mechanism was discussed in Chapter 1. The method call:
    alias_method_chain :target, :feature
    is equivalent to:
    alias_method :target_without_feature, :target
    alias_method :target, :target_with_feature
    One consequence is that thetarget_withfeaturemethod must exist before thealias
    method_chaincall. Punctuation (at the end of ?, !, and = methods) is properly moved to
    the end of the method names.

  • alias_attribute(new_name,old_name)aliases an ActiveRecord attribute to a new name,
    adding the getter, setter, and predicate (for example,person.name?) methods.


Delegation core_ext/module/delegation.rb


Thedelegate method provides a simple way to delegate one or more methods to an object:
class StringProxy
attr_accessor :target
delegate :to_s, :to => :target
def initialize(target)
@target = target
end
end


proxy = StringProxy.new("Hello World!")
proxy.to_s # => "Hello World!"
proxy.target = "Goodbye World"
proxy.to_s # => "Goodbye World"

More detailed control over delegation can be obtained withDelegatorfrom the standard
library.


Introspection core_ext/module/inclusion.rb,core_ext/module/introspection.rb



  • Module#included_in_classesiterates over all classes (usingObjectSpace), collecting the
    classes and modules in which the receiver is included.
    Enumerable.included_in_classes.include? Array # => true
    Enumerable.included_in_classes.include? String # => true
    Enumerable.included_in_classes.include? Numeric # => false

  • Module#parent andModule#parents inspect the module namespace hierarchy:
    module A
    module B
    class C
    end
    end
    end

Free download pdf