Skip to content

Instantly share code, notes, and snippets.

@bdehamer
Created July 5, 2012 23:38
Show Gist options
  • Save bdehamer/3057143 to your computer and use it in GitHub Desktop.
Save bdehamer/3057143 to your computer and use it in GitHub Desktop.
Fog Model Observer
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
@bdehamer
Copy link
Author

bdehamer commented Jul 5, 2012

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.

@dharmamike
Copy link

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