Created
October 31, 2017 02:02
-
-
Save spacebat/8705f649509aec8fd537ba7d32d7983c to your computer and use it in GitHub Desktop.
Module, class and a default instance
This file contains 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 | |
# Attempt to make a module with methods that default to using state in | |
# a default instance of a class within the module, yet allow for | |
# specific instances of the class to be produced with their own state, | |
# that share these same module methods. It boils down to using the | |
# module method this in place of self. | |
module Moo | |
extend self | |
@@this = nil | |
class C | |
include Moo | |
def say(*args) | |
puts "This #{this} is saying: #{args}" | |
end | |
end | |
def this | |
if self.is_a? Moo::C | |
self | |
else | |
@@this ||= C.new | |
end | |
end | |
def bar | |
this.say "self=#{self}, this: #{this}" | |
end | |
end | |
if __FILE__ == $0 | |
Moo.bar | |
Moo::C.new.bar | |
Moo.bar | |
end |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment