DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Lance has posted 24 posts at DZone. View Full User Profile

Ruby Metaprogramming - Subclass A Method With Before/After Callbacks And Alias_method

08.14.2010
| 2905 views |
  • submit to reddit
        
require 'rubygems'
require 'active_model'

class BaseModel
  extend ActiveModel::Callbacks

  define_model_callbacks :save
  before_save { puts "[save:before]"}
  after_save { puts "[save:after]"}

  def do_save; end
  def save
    _run_save_callbacks do
      do_save
    end
  end
  alias_method :superclass_save, :save
end

class SomeModel < BaseModel
  def save
    puts "[saving...]"
    true
  end
end

SomeModel.class_eval do
  alias_method :subclass_save, :save
  alias_method :do_save, :subclass_save
  alias_method :save, :superclass_save
end

model = SomeModel.new
model.save