Skip to content

Instantly share code, notes, and snippets.

@ahoward
Created September 13, 2016 22:17
Show Gist options
  • Select an option

  • Save ahoward/73b7a0210c8dc35466643c89ba2562ab to your computer and use it in GitHub Desktop.

Select an option

Save ahoward/73b7a0210c8dc35466643c89ba2562ab to your computer and use it in GitHub Desktop.
# mongoid style
#
module A
end
class B
include A
end
B.new
# active_record style
#
class C
end
class D < C
end
D.new
# but we have to choose - even though we don't know how client code wants to
# make re-use of our code: composition or inheritence...
#
# however, in ruby, the distintion is artifitial, a single thing can act as a
# module and class easily - allowing client code to re-use your work depending
# on how their own code is organized. this could easily be done at the C
# level and simply do away with the need to decide in library code.
#
module M
module ClassMethods
def foo
40
end
end
module InstanceMethods
def bar
2
end
end
def M.included(other)
super
ensure
other.send(:extend, ClassMethods)
other.send(:include, InstanceMethods)
end
class Base
include M
end
def M.base
Base
end
def M.new(*args, &block)
base.new(*args, &block)
end
end
class N
include M
end
class O < M.base
end
n = N.new
o = O.new
p n.class.foo + n.bar #=> 42
p o.class.foo + o.bar #=> 42
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment