阅读Paperclip源码,发现里面有一个不错的callback机制,如下:
def has_attached_file name, options = {} include InstanceMethods write_inheritable_attribute(:attachment_definitions, {}) if attachment_definitions.nil? attachment_definitions[name] = {:validations => []}.merge(options) after_save :save_attached_files before_destroy :destroy_attached_files define_paperclip_callbacks :post_process, :"#{name}_post_process" 。。。。。。。 end
来看看define_paperclip_callbacks方法,在CallbackCompatability这个module中有定义:
module Rails3 def self.included(base) base.extend(Defining) base.send(:include, Running) end module Defining def define_paperclip_callbacks(*callbacks) define_callbacks *[callbacks, {:terminator => "result == false"}].flatten callbacks.each do |callback| eval <<-end_callbacks def before_#{callback}(*args, &blk) set_callback(:#{callback}, :before, *args, &blk) end def after_#{callback}(*args, &blk) set_callback(:#{callback}, :after, *args, &blk) end end_callbacks end end end module Running def run_paperclip_callbacks(callback, opts = nil, &block) run_callbacks(callback, opts, &block) end end end
在看看set_callback是怎么被调用的
module Glue def self.included base #:nodoc: base.extend ClassMethods if base.respond_to?("set_callback") base.send :include, Paperclip::CallbackCompatability::Rails3 else base.send :include, Paperclip::CallbackCompatability::Rails21 end end end
关键在于
run_callbacks(callback, opts, &block)
直接调用rails3的api,完毕后回调block,在block继续自己的业务逻辑