Sha256: 720b699c7db616b9ec91a960f41fbaf1b5b06f2a01ef3d48e8b82613e38e711e

Contents?: true

Size: 1.48 KB

Versions: 13

Compression:

Stored size: 1.48 KB

Contents

module Sequel
  class Model
    HOOKS = [
      :after_initialize,
      :before_create,
      :after_create,
      :before_update,
      :after_update,
      :before_save,
      :after_save,
      :before_destroy,
      :after_destroy
    ]
    
    # Some fancy code generation here in order to define the hook class methods...
    HOOK_METHOD_STR = %Q{
      def self.%s(method = nil, &block)
        unless block
          (raise SequelError, 'No hook method specified') unless method
          block = proc {send method}
        end
        add_hook(%s, &block)
      end
    }
    
    def self.def_hook_method(m) #:nodoc:
      instance_eval(HOOK_METHOD_STR % [m.to_s, m.inspect])
    end
    
    HOOKS.each {|h| define_method(h) {}}
    HOOKS.each {|h| def_hook_method(h)}
    
    # Returns the hooks hash for the model class.
    def self.hooks #:nodoc:
      @hooks ||= Hash.new {|h, k| h[k] = []}
    end
    
    def self.add_hook(hook, &block) #:nodoc:
      chain = hooks[hook]
      chain << block
      define_method(hook) do 
        return false if super == false
        chain.each {|h| break false if instance_eval(&h) == false}
      end
    end

    # Returns true if the model class or any of its ancestors have defined
    # hooks for the given hook key. Notice that this method cannot detect 
    # hooks defined using overridden methods.
    def self.has_hooks?(key)
      has = hooks[key] && !hooks[key].empty?
      has || ((self != Model) && superclass.has_hooks?(key))
    end
  end
end

Version data entries

13 entries across 13 versions & 2 rubygems

Version Path
sequel-1.4.0 lib/sequel_model/hooks.rb
sequel_model-0.4.2 lib/sequel_model/hooks.rb
sequel_model-0.5.0.1 lib/sequel_model/hooks.rb
sequel_model-0.3.3 lib/sequel_model/hooks.rb
sequel_model-0.5 lib/sequel_model/hooks.rb
sequel_model-0.3.2 lib/sequel_model/hooks.rb
sequel_model-0.5.0.2 lib/sequel_model/hooks.rb
sequel_model-0.4 lib/sequel_model/hooks.rb
sequel_model-0.2 lib/sequel_model/hooks.rb
sequel_model-0.3 lib/sequel_model/hooks.rb
sequel_model-0.3.1 lib/sequel_model/hooks.rb
sequel_model-0.3.2.1 lib/sequel_model/hooks.rb
sequel_model-0.4.1 lib/sequel_model/hooks.rb