Skip to content

Instantly share code, notes, and snippets.

@mwlang
Last active April 8, 2021 13:29
Show Gist options
  • Save mwlang/49bf3b55d4d7eefb30d2a929726075b0 to your computer and use it in GitHub Desktop.
Save mwlang/49bf3b55d4d7eefb30d2a929726075b0 to your computer and use it in GitHub Desktop.
Example of how to handle varying method argument signatures across Rubies 2.2 - 3.0 and jRuby using ruby2_keywords. Run using Ruby's warn flag like so:
>> ruby -w delegating.rb
Foo says...
["hello", "world"]
========================================
Bar says...
["yo", "world"]
{}
****************************************
Foobar says...
"howdy"
"folks"
########################################
********************************************************************************
Tracing Foo
Foo says...
["hello", "world"]
========================================
Tracing Bar
Bar says...
["yo", "world"]
{}
****************************************
Tracing Foobar
Foobar says...
"howdy"
"folks"
########################################
class Foo
def speak(*args, &block)
puts "Foo says..."
puts args.inspect
yield
end
end
class Bar
def speak(*args, **kwargs, &block)
puts "Bar says..."
puts args.inspect
puts kwargs.inspect
yield
end
end
class Foobar
def speak(what, how:, &block)
puts "Foobar says..."
puts what.inspect
puts how.inspect
yield
end
end
Foo.new.speak("hello", "world") { puts "=" * 40 }
Bar.new.speak("yo", "world") { puts "*" * 40 }
Foobar.new.speak("howdy", how: "folks") { puts "#" * 40 }
def trace_the_speaker speaker_class
speaker_class.class_eval do
def speak_loudly(*args, &block)
puts "Tracing #{self.class}"
speak_normally(*args, &block)
end
alias_method :speak_normally, :speak
alias_method :speak, :speak_loudly
ruby2_keywords(:speak_loudly) if respond_to?(:ruby2_keywords, true)
end
end
puts "*" * 80
trace_the_speaker(Foo)
trace_the_speaker(Bar)
trace_the_speaker(Foobar)
Foo.new.speak("hello", "world") { puts "=" * 40 }
Bar.new.speak("yo", "world") { puts "*" * 40 }
Foobar.new.speak("howdy", how: "folks") { puts "#" * 40 }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment