[ruby-core:121535] [Ruby Feature#14565] Simpler, one-liner, failsafe require in ruby? [Suggested names: require_failsafe, require_safe, require_try, require_add)
From:
deivid via ruby-core <ruby-core@...>
Date:
2025-04-03 11:38:46 UTC
List:
ruby-core #121535
Issue #14565 has been updated by deivid (David Rodr=EDguez).
I like `require "rubocop-rspec", optional: true` idea from https://bugs.rub=
y-lang.org/issues/20714.
I wonder if a `nil` return value for `require ..., optional: true` when the=
feature was not available would make sense, and would enable users to act =
accordingly?
----------------------------------------
Feature #14565: Simpler, one-liner, failsafe require in ruby? [Suggested na=
mes: require_failsafe, require_safe, require_try, require_add)
https://bugs.ruby-lang.org/issues/14565#change-112562
* Author: shevegen (Robert A. Heiler)
* Status: Open
----------------------------------------
I have quite a bit of code like this:
```ruby
begin
require 'x/tools/cdrskin.rb'
rescue LoadError; end
```
I also use the longer variant, e.g.,
```ruby
begin
require 'foobar'
rescue LoadError
puts 'project foobar is not available - consider '\
'installing it via gem install foobar'
end
```
Often, I do not need to inform the user about missing gems/projects that ar=
e tiny and not very important. In my larger ruby projects, I handle cases w=
here a smaller project is not available or available, so I can proceed eith=
er way. It is a bit pointless to notify the user when that is me; that is w=
hy I would like to have a one-liner.
I am thinking of an API such as any of the following:
require_failsafe
require_safe
require_try
require_add
This is for loading with a rescue LoadError without notification. If I need=
to notify a user then I am fine with the longer variant.
If anyone has better names, feel free to add them! I think people are more =
likely to remember the require-family, e. g. require 'foo.rb' or require_re=
lative 'bar.rb' and so forth.
---
I also wanted to propose a stronger `require`/`import`, including the possi=
bility to refer to `.rb` files without a hardcoded path (if the .rb file is=
moved,
all explicit requires to it, in particular from external projects, would ha=
ve to change; and my vague idea is to replace this with some kind of projec=
t-specific way to
"label" files and load these files based on these "labels", but that is for=
another suggestion; I only want to mention it because Hiroshi Shibata made=
some suggestion as extension to require, and I think the use case he menti=
oned may also be useful to see whether ruby may get a stronger "load code i=
n files" functionality for ruby 3.x eventually).
--=20
https://bugs.ruby-lang.org/
______________________________________________
ruby-core mailing list -- ruby-core@ml.ruby-lang.org
To unsubscribe send an email to ruby-core-leave@ml.ruby-lang.org
ruby-core info -- https://ml.ruby-lang.org/mailman3/lists/ruby-core.ml.rub=
y-lang.org/