Skip to content

Instantly share code, notes, and snippets.

@keithrbennett
Last active September 15, 2022 15:01
Show Gist options
  • Save keithrbennett/4f3afd8b43e9d202c7da5a2d2f75d95f to your computer and use it in GitHub Desktop.
Save keithrbennett/4f3afd8b43e9d202c7da5a2d2f75d95f to your computer and use it in GitHub Desktop.
Illustrates forcing inclusion of a module by another included module in Ruby.
#!/usr/bin/env ruby
# From solution at https://stackoverflow.com/questions/73676857/guaranteeing-that-module-includer-classes-include-another-module-in-ruby.
module M1
def m1; puts 'M1 was included by M2.'; end
end
module M2
def self.included(including_class)
including_class.class_exec { include M1 }
end
end
class C
include M2
end
C.new.m1 # => M1 was included by M2.
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment