Class: ActiveModel::Observer

Inherits:
Object
  • Object
show all
Includes:
Singleton
Defined in:
activemodel/lib/active_model/observing.rb

Class Attribute Summary (collapse)

Instance Attribute Summary (collapse)

Class Method Summary (collapse)

Instance Method Summary (collapse)

Constructor Details

- (Observer) initialize

Start observing the declared classes and their subclasses.



76
77
78
79
# File 'activemodel/lib/active_model/observing.rb', line 76

def initialize
  self.observed_classes = self.class.models if self.class.models
  observed_classes.each { |klass| klass.add_observer(self) }
end

Class Attribute Details

+ (Object) models

Returns the value of attribute models



50
51
52
# File 'activemodel/lib/active_model/observing.rb', line 50

def models
  @models
end

Instance Attribute Details

- (Object) observed_classes=(value)

Sets the attribute observed_classes



47
48
49
# File 'activemodel/lib/active_model/observing.rb', line 47

def observed_classes=(value)
  @observed_classes = value
end

Class Method Details

+ (Object) observe(*models)

Attaches the observer to the supplied model classes.



52
53
54
55
# File 'activemodel/lib/active_model/observing.rb', line 52

def observe(*models)
  @models = models.flatten
  @models.collect! { |model| model.respond_to?(:to_sym) ? model.to_s.camelize.constantize : model }
end

+ (Object) observed_class

The class observed by default is inferred from the observer's class name:

assert_equal [Person], PersonObserver.observed_class


66
67
68
69
70
71
72
# File 'activemodel/lib/active_model/observing.rb', line 66

def observed_class
  if observed_class_name
    observed_class_name.constantize
  else
    nil
  end
end

+ (Object) observed_class_name



57
58
59
60
61
62
# File 'activemodel/lib/active_model/observing.rb', line 57

def observed_class_name
  @observed_class_name ||= 
    if guessed_name = name.scan(/(.*)Observer/)[0]
      @observed_class_name = guessed_name[0]
    end
end

Instance Method Details

- (Object) observed_class_inherited(subclass)

Special method sent by the observed class when it is inherited. Passes the new subclass.



88
89
90
91
# File 'activemodel/lib/active_model/observing.rb', line 88

def observed_class_inherited(subclass) #:nodoc:
  self.class.observe(observed_classes + [subclass])
  subclass.add_observer(self)
end

- (Object) update(observed_method, object)

Send observed_method(object) if the method exists.



82
83
84
# File 'activemodel/lib/active_model/observing.rb', line 82

def update(observed_method, object) #:nodoc:
  send(observed_method, object) if respond_to?(observed_method)
end