Skip to content

Instantly share code, notes, and snippets.

@ahoward
Created July 25, 2011 19:33
Show Gist options
  • Star 6 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save ahoward/1104973 to your computer and use it in GitHub Desktop.
Save ahoward/1104973 to your computer and use it in GitHub Desktop.
#! /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