Skip to content

Instantly share code, notes, and snippets.

@tomash
Last active December 18, 2015 08:39
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save tomash/5755386 to your computer and use it in GitHub Desktop.
Save tomash/5755386 to your computer and use it in GitHub Desktop.
Class variable defined on parent class level being set on the parent class level. Looks like a Ruby-powered "feature" of STI.
# seems to work properly, i.e. exporting_message callback does not pollute
require 'active_support/callbacks'
module Exportage
def self.included(base)
base.class_eval do
set_callback :save, :before, :exporting_message
def exporting_message
puts "exporting..."
end
end
end
end
class Record
include ActiveSupport::Callbacks
define_callbacks :save
def save
run_callbacks :save do
puts "- save"
end
end
end
class PersonRecord < Record
set_callback :save, :before, :saving_message
def saving_message
puts "saving..."
end
set_callback :save, :after do |object|
puts "saved"
end
end
class ProductRecord < Record
include Exportage
end
class CarRecord < Record
end
#record = Record.new
#record.save
#person = PersonRecord.new
#person.save
#car = CarRecord.new
#car.save
#product = ProductRecord.new
#product.save
# Class variable being set on the "parent class" level
module Exportage
def self.included(base)
base.class_eval do
after_save 'export_on_deferred_payment'
end
end
end
class BaseOrder
@@callbacks = []
def self.after_save(something)
@@callbacks << something
end
def self.print_callbacks
puts @@callbacks.inspect
end
end
class Order < BaseOrder
include Exportage
end
class EbayOrder < BaseOrder
end
# BaseOrder.print_callbacks
# >> ["export_on_deferred_payment"]
# Order.print_callbacks
# >> ["export_on_deferred_payment"]
# EbayOrder.print_callbacks
# >> ["export_on_deferred_payment"]
@apotonick
Copy link

AS::Callbacks uses a class instance variable to save the callbacks, whereas you use a class variable!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment