Sha256: b5aeb44f87315d543c1ca69e6a7afec7de39d0cc225cc5753546972fb5fd8c37

Contents?: true

Size: 1.82 KB

Versions: 2

Compression:

Stored size: 1.82 KB

Contents

module AssetCloud
  
  module Callbacks
    
    CALLBACKS = [:delete, :write]
    
    def self.included(base)
           
      CALLBACKS.each do |method|
         code = <<-"end_eval"
        
         def self.before_#{method}(*callbacks, &block)
           callbacks << block if block_given?
           write_inheritable_array(:before_#{method}, callbacks)
         end          
        
         def self.after_#{method}(*callbacks, &block)
           callbacks << block if block_given?
           write_inheritable_array(:after_#{method}, callbacks)
         end          
        
         
         def #{method}_with_callbacks(*args)
           if execute_callbacks(:before_#{method}, args)
             result = #{method}_without_callbacks(*args)
             execute_callbacks(:after_#{method}, args)         
           end
           result
         end    

         alias_method_chain :#{method}, 'callbacks'         
        end_eval
                        
        base.class_eval code, __FILE__, __LINE__        
      end      
    end
    
    def execute_callbacks(symbol, args)
      callbacks_for(symbol).each do |callback|
        
        result = case callback
        when Symbol
          self.send(callback, *args)
        when Proc, Method
          callback.call(self, *args)
        else
          if callback.respond_to?(method)
            callback.send(method, self, *args)
          else
            raise StandardError, "Callbacks must be a symbol denoting the method to call, a string to be evaluated, a block to be invoked, or an object responding to the callback method."
          end          
        end  
        return false if result == false            
      end       
      true
    end               
      
    def callbacks_for(symbol)
      self.class.read_inheritable_attribute(symbol) || []
    end
  end
end

Version data entries

2 entries across 2 versions & 1 rubygems

Version Path
jamesmacaulay-asset_cloud-0.5.0 lib/asset_cloud/callbacks.rb
jamesmacaulay-asset_cloud-0.5.1 lib/asset_cloud/callbacks.rb