Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Where is SimpleDelegator in Ruby 2.7?

Tags:

ruby

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:

  • Ruby 2.4.6:
> ~/.rvm/rubies/ruby-2.4.6/bin/ruby p.rb 
Hello Sourav... It's Ruby 2.4.6 x86_64-linux
Sourav
  • Ruby 2.5.5:
> ~/.rvm/rubies/ruby-2.5.5/bin/ruby p.rb 
Hello Sourav... It's Ruby 2.5.5 x86_64-linux
Sourav
  • Ruby 2.6.3:
> ~/.rvm/rubies/ruby-2.6.3/bin/ruby p.rb 
Hello Sourav... It's Ruby 2.6.3 x86_64-linux
Sourav
  • Ruby 2.7.0:
> 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?

like image 897
S.Goswami Avatar asked Feb 28 '20 21:02

S.Goswami


1 Answers

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.

like image 171
cremno Avatar answered Oct 22 '22 10:10

cremno