observer.rb 1.5 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162
  1. #---
  2. # Excerpted from "Agile Web Development with Rails",
  3. # published by The Pragmatic Bookshelf.
  4. # Copyrights apply to this code. It may not be used to create training material,
  5. # courses, books, articles, and the like. Contact us if you are in doubt.
  6. # We make no guarantees that this code is fit for any purpose.
  7. # Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book information.
  8. #---
  9. #---
  10. # Excerpted from "Agile Web Development with Rails, 4rd Ed.",
  11. # published by The Pragmatic Bookshelf.
  12. # Copyrights apply to this code. It may not be used to create training material,
  13. # courses, books, articles, and the like. Contact us if you are in doubt.
  14. # We make no guarantees that this code is fit for any purpose.
  15. # Visit http://www.pragmaticprogrammer.com/titles/rails4 for more book information.
  16. #---
  17. $: << File.dirname(__FILE__)
  18. require "rubygems"
  19. require "active_record"
  20. require 'connect'
  21. ActiveRecord::Base.logger = Logger.new(STDERR)
  22. ActiveRecord::Schema.define do
  23. create_table :payments, :force => true do |t|
  24. end
  25. end
  26. class Order < ActiveRecord::Base
  27. end
  28. class Payment < ActiveRecord::Base
  29. end
  30. class Refund < ActiveRecord::Base
  31. end
  32. class OrderObserver < ActiveRecord::Observer
  33. def after_save(an_order)
  34. an_order.logger.info("Order #{an_order.id} created")
  35. end
  36. end
  37. OrderObserver.instance
  38. class AuditObserver < ActiveRecord::Observer
  39. observe Order, Payment, Refund
  40. def after_save(model)
  41. model.logger.info("[Audit] #{model.class.name} #{model.id} created")
  42. end
  43. end
  44. AuditObserver.instance
  45. o = Order.create
  46. p = Payment.create