Created
January 25, 2025 11:01
-
-
Save kigster/2665551a108f83921cd0aef0bc58634b to your computer and use it in GitHub Desktop.
Ruby Module/Class Interdependency playground
This file contains hidden or 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 | |
# © 2025 Konstantin Gredeskoul, All rights reserved. | |
# | |
# This script is a proof of concept to show how to use ActiveSupport::Concern | |
# to manage dependencies between modules and classes. The main idea is to use | |
# the included block to include the dependencies of a module, and the | |
# class_methods block to define class methods. | |
# | |
# Ultimately, the script prints all of the the methods of the Host, Bar, and | |
# Foo classes and modules to show the result of the concern implementation. | |
# | |
# Run simply as `ruby | |
require "active_support/concern" | |
module Foo | |
extend ActiveSupport::Concern | |
included do |base| | |
def hello | |
puts "hello" | |
end | |
def goodbye | |
puts "goodbye" | |
end | |
end | |
class_methods do | |
def included(another) | |
def ciao | |
puts "ciao! From #{another}" | |
end | |
end | |
def class_help | |
puts "class_help" | |
end | |
end | |
end | |
module Bar | |
include(Foo) | |
extend ActiveSupport::Concern | |
included do |base| | |
base.include(Foo) | |
end | |
end | |
class Host | |
include Bar # It works, now Bar takes care of its dependencies | |
end | |
require 'pp' | |
# ———————————————————————————-------------------------------- | |
def line; puts '—' * 40; end | |
def standard_methods | |
@standard_methods ||= [ | |
BasicObject.methods + | |
Object.methods + | |
Object.new.methods + | |
Module.methods + | |
Module.new.methods + | |
Kernel.methods + | |
::PP::ObjectMixin.methods + | |
PrettyPrint.methods | |
].sort.uniq | |
end | |
def ruby_functions(methods: []) | |
methods - standard_methods | |
end | |
puts "\nCLASS/MODULE METHODS\n" | |
print "Host: " | |
pp ruby_functions(methods: Host.methods) | |
print "Bar: " | |
pp ruby_functions(methods: Bar.methods) | |
print "Foo: " | |
pp ruby_functions(methods: Foo.methods) | |
line | |
puts "\nINSTANCE METHODS\n" | |
print "Host: " | |
pp ruby_functions(methods: Host.new.methods) | |
pp Host.ancestors |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment