Sha256: ff8e267dba7d1e3ca49516371baf2d70e4f2b117b67fef994fa3756f2947eeaf

Contents?: true

Size: 1.21 KB

Versions: 82

Compression:

Stored size: 1.21 KB

Contents

class MethodObserver
  
  attr_reader :target
  attr_accessor :result
  
  class ObserverCannotObserveTwiceError < StandardError
    def initialize(message = 'observer cannot observe twice')
      super
    end
  end
  
  def observe(target)
    raise ObserverCannotObserveTwiceError if @target
    @target = target
    make_observable(target)
  end
  
  def self.instances
    @instances ||= {}
  end
  
  def self.new(*args)
    o = super
    instances[o.object_id] = o
    o
  end
  
  private
    def make_observable(target)
      methods_to_observe.each do |method|
        target.instance_eval %{
          def #{method}(*args, &block)
            observer = #{self.class}.instances[#{self.object_id}]
            observer.send(:before_#{method}, *args, &block) if observer.respond_to? :before_#{method}
            observer.result = super
            observer.send(:after_#{method}, *args, &block) if observer.respond_to? :after_#{method}
            observer.result
          end
        }
      end
    end
    
    def methods_to_observe
      (methods_for(:before) + methods_for(:after)).uniq
    end
    
    def methods_for(name)
      methods.grep(/^#{name}_/).map { |n| n.to_s.gsub(/^#{name}_/, '').intern }
    end
end

Version data entries

82 entries across 82 versions & 9 rubygems

Version Path
radiant-rails3-0.1 lib/method_observer.rb
radiantcms-couchrest_model-0.2.4 lib/method_observer.rb
radiantcms-couchrest_model-0.2.2 lib/method_observer.rb
radiantcms-couchrest_model-0.2.1 lib/method_observer.rb
radiantcms-couchrest_model-0.2 lib/method_observer.rb
radiantcms-couchrest_model-0.1.9 lib/method_observer.rb
radiantcms-couchrest_model-0.1.8 lib/method_observer.rb
radiantcms-couchrest_model-0.1.7 lib/method_observer.rb
radiantcms-couchrest_model-0.1.6 lib/method_observer.rb
radiantcms-couchrest_model-0.1.5 lib/method_observer.rb
radiantcms-couchrest_model-0.1.4 lib/method_observer.rb
radiantcms-couchrest_model-0.1.3 lib/method_observer.rb
radiantcms-couchrest_model-0.1.2 lib/method_observer.rb
radiantcms-couchrest_model-0.1.1 lib/method_observer.rb
radiantcms-couchrest_model-0.1 lib/method_observer.rb
radiant-0.7.2 lib/method_observer.rb
spree-0.11.2 lib/method_observer.rb
spree-0.11.1 lib/method_observer.rb
radiant-0.9.1 lib/method_observer.rb
spree-0.11.0 lib/method_observer.rb