Created
July 25, 2011 19:33
-
-
Save ahoward/1104973 to your computer and use it in GitHub Desktop.
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
#! /usr/bin/env ruby | |
# this is best practice for writing mixins. the deferred evaluation is more | |
# powerful that the approach of ClassMethods/InstanceMethods as modules too | |
# | |
module Mixin | |
# put your class level code in here | |
# | |
ClassMethods = proc do | |
# if you do anything with constants you'll need dynamic scoping since, | |
# otherwise, a const's scope is determined lexically... | |
# | |
const_set(:Const, self.name) | |
def foo | |
const_get(:Const) | |
end | |
end | |
# put your instance methods here | |
# | |
InstanceMethods = proc do | |
def bar | |
self.class.name.downcase | |
end | |
end | |
# trigger on mixin. the order may need reversed for ruby 1.9.2 | |
# | |
def Mixin.included(other) | |
super | |
ensure | |
other.send(:instance_eval, &ClassMethods) | |
other.send(:module_eval, &InstanceMethods) | |
end | |
end | |
# sample usage | |
# | |
if $0 == __FILE__ | |
class A | |
include Mixin | |
end | |
class B | |
include Mixin | |
end | |
p A.foo #=> "A" | |
p A.new.bar #=> "a" | |
p B.foo #=> "B" | |
p B.new.bar #=> "b" | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment