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

#initializeObserver

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

.modelsObject

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

#observed_classes=(value) ⇒ Object

Sets the attribute observed_classes

Parameters:

  • value

    the value to set the attribute observed_classes to.



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

def observed_classes=(value)
  @observed_classes = value
end

Class Method Details

.observe(*models) ⇒ Object

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

.observed_classObject

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

.observed_class_nameObject



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

#observed_class_inherited(subclass) ⇒ Object

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

#update(observed_method, object) ⇒ 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