Ruby Metaprogramming - Subclass a Method with Before/After Callbacks and alias_method


/ Published in: Ruby
Save to your folder(s)



Copy this code and paste it in your HTML
  1. require 'rubygems'
  2. require 'active_model'
  3.  
  4. class BaseModel
  5. extend ActiveModel::Callbacks
  6.  
  7. define_model_callbacks :save
  8. before_save { puts "[save:before]"}
  9. after_save { puts "[save:after]"}
  10.  
  11. def do_save; end
  12. def save
  13. _run_save_callbacks do
  14. do_save
  15. end
  16. end
  17. alias_method :superclass_save, :save
  18. end
  19.  
  20. class SomeModel < BaseModel
  21. def save
  22. puts "[saving...]"
  23. true
  24. end
  25. end
  26.  
  27. SomeModel.class_eval do
  28. alias_method :subclass_save, :save
  29. alias_method :do_save, :subclass_save
  30. alias_method :save, :superclass_save
  31. end
  32.  
  33. model = SomeModel.new
  34. model.save

URL: ruby-metaprogramming-subclass-a-method-with-before-after-callbacks-and-alias-method

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.