Skip to content

Commit

Permalink
exchange wasteful module creation for a hash
Browse files Browse the repository at this point in the history
  • Loading branch information
cldwalker committed Apr 16, 2011
1 parent 01f2166 commit 8ceb458
Showing 1 changed file with 16 additions and 9 deletions.
25 changes: 16 additions & 9 deletions lib/watchdog.rb
@@ -1,4 +1,8 @@
module Watchdog
# Maps objects or modules to their extension modules
class <<self; attr_accessor :extensions; end
self.extensions = {}

class Error < StandardError
def initialize(meth, from, to)
super "#{from} can't add method '#{meth}' to #{to}"
Expand All @@ -7,17 +11,20 @@ def initialize(meth, from, to)
class ExtendError < Error; end
class IncludeError < Error; end

def self.guard(mod, guarded)
guard_mod = Module.new { class << self; attr_accessor :existing; end }
guard_mod.existing = mod
guard_meth = guarded.is_a?(Module) ? :method_added : :singleton_method_added
guard_mod.send(:define_method, guard_meth) do |meth|
if guard_mod.existing.instance_methods.include?(meth)
raise Watchdog::Error.new(meth, self, mod)
module GermanShepard
[:singleton_method_added, :method_added].each do |m|
define_method(m) do |meth|
if Watchdog.extensions[self].instance_methods.include?(meth)
raise Watchdog::Error.new(meth, self, Watchdog.extensions[self])
end
super
end
super
end
guarded.extend guard_mod
end

def self.guard(mod, guarded)
extensions[guarded] = mod
guarded.extend GermanShepard
end

def append_features(mod)
Expand Down

0 comments on commit 8ceb458

Please sign in to comment.