Over a million developers have joined DZone.
{{announcement.body}}
{{announcement.title}}

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

DZone's Guide to

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

·
Free Resource
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
Topics:

Opinions expressed by DZone contributors are their own.

{{ parent.title || parent.header.title}}

{{ parent.tldr }}

{{ parent.urlSource.name }}