Skip to content

Instantly share code, notes, and snippets.

@dan-manges
Created November 23, 2009 03:36
Show Gist options
  • Save dan-manges/240872 to your computer and use it in GitHub Desktop.
Save dan-manges/240872 to your computer and use it in GitHub Desktop.
require "rubygems"
gem "mixology", "0.2.0"
require "mixology"
Mixology.class_eval do
def mixin_with_hook(mod)
result = mixin_without_hook(mod)
if mod.respond_to?(:mixed_into)
mod.mixed_into(self)
end
result
end
alias_method :mixin_without_hook, :mixin
alias_method :mixin, :mixin_with_hook
def unmix_with_hook(mod)
result = unmix_without_hook(mod)
if mod.respond_to?(:unmixed_from)
mod.unmixed_from(self)
end
result
end
alias_method :unmix_without_hook, :unmix
alias_method :unmix, :unmix_with_hook
end
require "test/unit"
class MixologyHookTest < Test::Unit::TestCase
def self.test(description, &block)
define_method "test_#{description}", &block
end
test "mixin calls the mixed_into hook if it's defined" do
module_with_hook = Module.new do
class << self
attr_reader :object_passed_to_hook
end
def self.mixed_into(object)
@object_passed_to_hook = object
end
end
o = Object.new
o.mixin module_with_hook
assert_equal o, module_with_hook.object_passed_to_hook
end
test "mixin doesn't call hook if it's not defined" do
assert_nothing_raised do
o = Object.new
o.mixin Module.new
end
end
test "mixin returns same value regardless of whether it called the hook or not" do
module_with_hook = Module.new do
def self.mixed_into(object)
@hook_called = true
end
def self.hook_called?
@hook_called
end
end
module_without_hook = Module.new
o = Object.new
return_value_without_hook = o.mixin(module_without_hook)
return_value_with_hook = o.mixin(module_with_hook)
assert_equal return_value_with_hook, return_value_without_hook
end
test "unmix calls the unmixed_from hook if it's defined" do
module_with_hook = Module.new do
class << self
attr_reader :object_passed_to_hook
end
def self.unmixed_from(object)
@object_passed_to_hook = object
end
end
o = Object.new
o.mixin module_with_hook
o.unmix module_with_hook
assert_equal o, module_with_hook.object_passed_to_hook
end
test "unmixin doesn't call hook if it's not defined" do
assert_nothing_raised do
o = Object.new
mod = Module.new
o.mixin mod
o.unmix mod
end
end
test "unmix returns same value regardless of whether it called the hook or not" do
module_with_hook = Module.new do
def self.mixed_into(object)
@hook_called = true
end
def self.hook_called?
@hook_called
end
end
module_without_hook = Module.new
o = Object.new
o.mixin(module_without_hook)
return_value_without_hook = o.unmix(module_without_hook)
o.mixin(module_with_hook)
return_value_with_hook = o.unmix(module_with_hook)
assert_equal return_value_with_hook, return_value_without_hook
end
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment