Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
#! /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
You can’t perform that action at this time.