Skip to content

Instantly share code, notes, and snippets.

@okuramasafumi
Created March 25, 2022 16:16
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save okuramasafumi/146cea1e32fcb61ca3836e7e6dd71737 to your computer and use it in GitHub Desktop.
Save okuramasafumi/146cea1e32fcb61ca3836e7e6dd71737 to your computer and use it in GitHub Desktop.
Mixable method where we can sort method call sequence
class Module
def define_mixable_method(name:, calls:, main:)
define_method(name) do |&block|
method_candidates = calls.map {|name| method(name) }
block.call(main, method_candidates).each do |m|
m.call
end
end
end
end
class Foo
def a
puts 'a'
end
def b
puts 'b'
end
define_mixable_method(name: :y, calls: [:a, :b], main: -> { puts 'y' })
end
foo = Foo.new
foo.y do |main, candidates|
[main] + candidates.reverse
end
# => y, b, a
foo.y do |main, candidates|
candidates + [main]
end
# => a, b, y
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment