I have been using the SimpleDelegator class for various things. But I noticed, Ruby 2.7 (ArchLinux x86_64) doesn't come with the SimpleDelegator class (no Delegator either).
My program:
#!/usr/bin/ruby -w
class OutputDecorator < SimpleDelegator
def puts(*args)
STDOUT.write "Hello #{args.join}... It's Ruby #{RUBY_VERSION} #{RUBY_PLATFORM}\n"
end
end
$stdout = OutputDecorator.new($stdout)
$stdout.puts('Sourav')
$stdout = $stdout.__getobj__
$stdout.puts('Sourav')
Running with:
> ~/.rvm/rubies/ruby-2.4.6/bin/ruby p.rb
Hello Sourav... It's Ruby 2.4.6 x86_64-linux
Sourav
> ~/.rvm/rubies/ruby-2.5.5/bin/ruby p.rb
Hello Sourav... It's Ruby 2.5.5 x86_64-linux
Sourav
> ~/.rvm/rubies/ruby-2.6.3/bin/ruby p.rb
Hello Sourav... It's Ruby 2.6.3 x86_64-linux
Sourav
> ruby p.rb
Traceback (most recent call last):
p.rb:2:in `<main>': uninitialized constant SimpleDelegator (NameError)
Is there any new alternatives to SimpleDelegator in Ruby 2.7?
The Delegator
and SimpleDelegator
classes aren't core classes like Array
or Mutex
. They're part of the delegate
standard library which needs to be loaded first: require 'delegate'
.
It happened to work in older Ruby versions as they came with an older RubyGems version by default. RubyGems is automatically loaded since Ruby 1.9 and until 3.1.0 that meant delegate
was loaded indirectly. Updating RubyGems or running ruby
with --disable=gems
should cause the exact same issue with Ruby <= 2.6 too. irb
also loads several standard libraries: delegate
but also timeout
and many more.
Programming languages with a similar mechanism like C++ also have this issue: instead of load
/require
there's #include
, including a standard library header might include another one, then a newer version might not include the other header anymore and user code relying on the old behavior fails to compile.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With