lib/faye-rails/controller/observer_factory.rb in faye-rails-1.0.3 vs lib/faye-rails/controller/observer_factory.rb in faye-rails-1.0.4
- old
+ new
@@ -1,50 +1,35 @@
require 'active_record'
module FayeRails
class Controller
- # Module creates ActiveRecord::Observer instances
+ # Define callbacks into any ORM model.
module ObserverFactory
# Create
def self.define(klass, method_name, &block)
- # Make a name for the observer
- klass_observer_name = "#{klass.to_s}Observer"
+ # Make a name for the callback module
+ klass_callbacks_name = "#{klass.name}Callbacks"
- # Load the observer if one exists
- klass_observer = ObserverFactory.observer(klass_observer_name)
+ # Load the callback module if exists
+ unless (klass_callbacks = ObserverFactory.observer(klass_callbacks_name))
+ # Define callback module if one does not exist
+ klass_callbacks = Object.const_set(klass_callbacks_name, Module.new)
+ end
- new_observer = klass_observer.nil?
-
- # Create a new observer if one does not exist
- klass_observer = Object.const_set(klass_observer_name, Class.new(ActiveRecord::Observer) do
- # TODO Work around this hack.
- # Have to define all of the available methods when creating the Observer class for the
- # first time. The methods can then be overriden by the observe DSL. However if they
- # are not first defined then they will not be registerable.
- [:before_validation, :after_validation, :before_save, :before_create, :after_create, :after_save, :after_commit].each do |arg|
- send :define_method, arg do |temp|
- end
- end
- end) if new_observer
-
# Add the method to the observer
- klass_observer.instance_eval do
+ klass_callbacks.instance_eval do
define_method(method_name, &block)
end
- # Add the observer if needed
- if new_observer
- ActiveRecord::Base.observers << klass_observer
- end
-
- ActiveRecord::Base.instantiate_observers
+ # Bind model callback
+ klass.send(method_name, klass_callbacks.extend(klass_callbacks))
end
- def self.observer(class_name)
- klass = Module.const_get(class_name)
- return klass if klass.is_a?(Class)
+ def self.observer(module_name)
+ ref = Module.const_get(module_name)
+ return ref if ref.is_a?(Module)
nil
rescue
nil
end