Last active
December 18, 2015 08:39
-
-
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.
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
# 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"] |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
AS::Callbacks
uses a class instance variable to save the callbacks, whereas you use a class variable!