Last active
August 25, 2023 19:46
-
-
Save matsales28/a224e2c0a00b51ee5b87c5f5ff8e123c to your computer and use it in GitHub Desktop.
Ruby modules with arguments
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
class Callable < Module | |
def self.[](method) | |
new(method) | |
end | |
def initialize(method) | |
@method = method | |
end | |
def included(base) | |
method = @method | |
base.class_eval do | |
define_singleton_method(method) do |*args, **kwargs| | |
new(*args, **kwargs).send(method) | |
end | |
end | |
end | |
end | |
class Hello | |
include Callable[:perform] | |
attr_reader :name | |
def initialize(name:) | |
@name = name | |
end | |
def perform | |
p "Hello #{name}" | |
end | |
end | |
Hello.perform(name: "Matheus") # => "Hello Matheus" |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment