active_record回调过程

activesupport-2.3.4/lib/active_support/callbacks.rb

activerecord-2.3.4/lib/active_record/callbacks.rb

activerecord-2.3.4/lib/active_record/transactions.rb

models/topic.rb

activerecord-2.3.4/lib/active_record/callbacks.rb

Ruby代码
  1. [:create_or_update, :valid?, :create, :update, :destroy].each do |method|
  2. base.send :alias_method_chain, method, :callbacks
  3. end
Ruby代码
  1. def after_create() end
  2. def create_with_callbacks #:nodoc:
  3. return false if callback(:before_create) == false
  4. result = create_without_callbacks
  5. callback(:after_create)
  6. result
  7. end
  8. private :create_with_callbacks

activesupport-2.3.4/lib/active_support/callbacks.rb

Ruby代码
  1. def define_callbacks(*callbacks)
  2. callbacks.each do |callback|
  3. class_eval <<-"end_eval"
  4. def self.#{callback}(*methods, &block)
  5. callbacks = CallbackChain.build(:#{callback}, *methods, &block)
  6. @#{callback}_callbacks ||= CallbackChain.new
  7. @#{callback}_callbacks.concat callbacks
  8. end
  9. def self.#{callback}_callback_chain
  10. @#{callback}_callbacks ||= CallbackChain.new
  11. if superclass.respond_to?(:#{callback}_callback_chain)
  12. CallbackChain.new(
  13. superclass.#{callback}_callback_chain +
  14. @#{callback}_callbacks
  15. )
  16. else
  17. @#{callback}_callbacks
  18. end
  19. end
  20. end_eval
  21. end
  22. end
Ruby代码
  1. def run_callbacks(kind, options = {}, &block)
  2. self.class.send("#{kind}_callback_chain").run(self, options, &block)
  3. end

activerecord-2.3.4/lib/active_record/transactions.rb

Ruby代码
  1. base.class_eval do
  2. [:destroy, :save, :save!].each do |method|
  3. alias_method_chain method, :transactions
  4. end
  5. end

models/topic.rb

Ruby代码
  1. after_create :clear_cache

base.rb

Ruby代码
  1. def save
  2. create_or_update
  3. end
Ruby代码
  1. def create_or_update
  2. raise ReadOnlyRecord if readonly?
  3. result = new_record? ? create : update
  4. result != false
  5. end
Ruby代码
  1. def create
  2. if self.id.nil? && connection.prefetch_primary_key?(self.class.table_name)
  3. self.id = connection.next_sequence_value(self.class.sequence_name)
  4. end
  5. quoted_attributes = attributes_with_quotes
  6. statement = if quoted_attributes.empty?
  7. connection.empty_insert_statement(self.class.table_name)
  8. else
  9. "INSERT INTO #{self.class.quoted_table_name} " +
  10. "(#{quoted_column_names.join(', ')}) " +
  11. "VALUES(#{quoted_attributes.values.join(', ')})"
  12. end
  13. self.id = connection.insert(statement, "#{self.class.name} Create",
  14. self.class.primary_key, self.id, self.class.sequence_name)
  15. @new_record = false
  16. id
  17. end

posted @ 2010-02-24 15:13  麦飞  阅读(369)  评论(0编辑  收藏  举报