Skip to content

Instantly share code, notes, and snippets.

@spacebat
Created October 31, 2017 02:02
Show Gist options
  • Save spacebat/8705f649509aec8fd537ba7d32d7983c to your computer and use it in GitHub Desktop.
Save spacebat/8705f649509aec8fd537ba7d32d7983c to your computer and use it in GitHub Desktop.
Module, class and a default instance
#!/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