Created
July 5, 2012 23:38
-
-
Save bdehamer/3057143 to your computer and use it in GitHub Desktop.
Fog Model Observer
This file contains 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
require 'fog/hp/models/compute/address' | |
require 'fog/hp/models/compute/flavor' | |
require 'fog/hp/models/compute/image' | |
require 'fog/hp/models/compute/key_pair' | |
require 'fog/hp/models/compute/security_group' | |
require 'fog/hp/models/compute/server' | |
# Re-open Fog::Model | |
module Fog | |
class Model | |
include ActiveModel::Observing | |
# Alias initialize so that we can override, but still invoke the original implementation | |
alias_method :old_init, :initialize | |
def initialize(new_attributes = {}) | |
# Kinda like calling 'super' (if we could) | |
old_init(new_attributes) | |
# Notify observers that something is being initialized | |
notify_observers(:init) | |
end | |
end | |
end | |
class ModelObserver < ActiveModel::Observer | |
# Note that it won't work if you observe Fog::Model, you need to | |
# observe each of the specific classes you're interested in. | |
observe Fog::Compute::HP::Address, | |
Fog::Compute::HP::Flavor, | |
Fog::Compute::HP::Image, | |
Fog::Compute::HP::KeyPair, | |
Fog::Compute::HP::SecurityGroup, | |
Fog::Compute::HP::Server | |
# Callback for :init event | |
def init(x) | |
puts 'callback' | |
puts x.inspect | |
end | |
end | |
# This thing is a singleton, need to ensure it is initialized | |
ModelObserver.instance |
See http://api.rubyonrails.org/classes/ActiveModel/Observing/ClassMethods.html#method-i-observers-3D
My guess is we can skip line 48 by tying in some sort of initialization step where observers are declared and instantiated...something similar to config.active_record.observers line when using ActiveRecord
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Turns out you CANT user super when monkeypatching
http://stackoverflow.com/questions/4470108/when-monkey-patching-a-method-can-you-call-the-overridden-method-from-the-new-i
Hower alias_method DOES work.